获取交易失败错误:任何对等方均未提供有效响应

时间:2018-10-19 03:54:51

标签: node.js hyperledger-fabric hyperledger-composer

我得到的错误:     enrollSTudent Transaction Failed: text error trying invoke business network.Error: No valid responses from any peers. Response from attempted peer comms was an error: Error: transaction returned with failure: ReferenceError: NS is not defined. 我还遇到另一个错误,说有内存泄漏,但已修复。但是,我无法修复NS_是未定义的错误。这是我在下面使用的代码:

Chaincode.js

Chaincode.js

    use strict;
    /**
    * Write your transction processor functions here
    */
    var NS_UNIVERSITY   = 'org.gryphon.casestudy.university';
    var NS_COLLEGE      = 'org.gryphon.casestudy.college';
    var NS_STUDENT      = 'org.gryphon.casestudy.student';

    /**
     * create a new certificate entry
    * @param {org.gryphon.casestudy.university.issueCertificate} args - student 
    details
     * @transaction
     */
    function issueCertificate(args) {
    var certificateId = 'CertificateID-' + Date.now().toString();
    var certificate;
    var _assetRegistry;
    return getAssetRegistry(NS_UNIVERSITY + '.Certificate')
        .then(function (assetRegistry) {
            var factory = getFactory();

            certificate = factory.newResource(NS_UNIVERSITY, 'Certificate', 
    certificateId);
            certificate.issuedTo = args.studentName;
            certificate.programName = args.programName;
            certificate.issuedDate = new Date();
            certificate.certificateId = certificateId;
            return assetRegistry.add(certificate)
                .then(function (_res) {
                    return getParticipantRegistry(NS_STUDENT + '.Student');
                })
                .then(function (assetRegistry) {
                    _assetRegistry = assetRegistry;
                    return assetRegistry.get(args.studentID)
                    .then(function (certifiedStudent) {
                        certifiedStudent.certificateId = certificateId;

                    var event = factory.newEvent(NS_UNIVERSITY, 
    'certificateIssuedEvent');            
                    event.certificateId = certificateId;
                    emit(event);                                

                        return _assetRegistry.update(certifiedStudent)    
                    })
                .then(function (_res) {
                    return (_res);
                }).catch(
                    function (error) {
                            return (error);
                    });
                });
            });
    }

    /**
    * approve affiliation of college
    * @param {org.gryphon.casestudy.university.approveAffiliation} args - id of 
    college
    * @transaction
    */
    function approveAffiliation(args) {
    var registry;
    return getParticipantRegistry(NS_COLLEGE + '.College')
        .then(function (assetRegistry) {
            registry = assetRegistry;
            return assetRegistry.get(args.memberId)
                .then(function (college) {
                    college.isApproved = 1;
                    return registry.update(college)
                        .then(function (_res) {
                            return (_res);
                        }).catch(
                            function (error) {
                                return (error);
                            })
                });
        });
     }


    /**
    * Enroll Program to the college
    * @param {org.gryphon.casestudy.college.enrollProgram} args - id of college
    * @transaction
    */
    function enrollProgram(args) {
    var registry;
    return getParticipantRegistry(NS_COLLEGE + '.College')
        .then(function (assetRegistry) {
            registry = assetRegistry;
            return assetRegistry.get(args.collegeId)
                .then(function (college) {
                    if (college.isApproved == 1) {
                        college.programs.push(args.programName)
                    }
                    return registry.update(college)
                        .then(function (_res) {
                            console.log(_res)
                            return (_res);
                        }).catch(
                            function (error) {
                                return (error);
                            })
                });
        });
    }
    /**
     * Student can enroll them to a College and Program
     * @param {org.gryphon.casestudy.student.enrollStudent} args - student 
    details
     * @transaction
     */
    function enrollStudent(args) {
    return getParticipantRegistry(NS_STUDENT + '.Student')
        .then(function (assetRegistry) {
            var factory = getFactory();
            var studentId = 'Student-' + Date.now().toString();
            var student = factory.newResource(NS_STUDENT, 'Student', studentId);
            student.name = args.name;
            student.dob = args.dob;
            student.memberId = studentId;
            student.programName = args.programName;
            student.collegeName = args.collegeName;
            return assetRegistry.add(student)
                .then(function (_res) {
                    return (_res);
                }).catch(
                    function (error) {
                        return (error);
                    });
        });
    }

    /**
    * College can request Affiliation to the University
    * @param {org.gryphon.casestudy.college.requestAffiliation} args - name of 
    college
    * @transaction
    */
    function requestAffiliation(args) {
    return getParticipantRegistry(NS_COLLEGE + '.College')
        .then(function (assetRegistry) {
            var factory = getFactory();
            var collegeId = 'College-' + Date.now().toString();
            var college = factory.newResource(NS_COLLEGE, 'College', collegeId);
            college.name = args.name;
            college.memberId = collegeId;
            college.isApproved = 0;
            college.programs = [];
            return assetRegistry.add(college)
                .then(function (_res) {
                    return (_res);
                }).catch(
                    function (error) {
                        return (error);
                    });
        });
    }

events.js文件:

function requestAffiliation() {
    // Show Progress untill the task is complete
    document.getElementById('college_progress').innerHTML = '<img src="./icons/progress.gif"/>';

    // Get the attributes from the UI i.e College Name
    let college_name = document.getElementById('college_name').value;

    // Set the Payload for the Post restapi call
    let options = { 'college_name': college_name };
    {
        // Use Async ajax call to post a request to the Client App
        $.when($.post('/composer/client/requestAffiliation', options)).done(function (_res) {

            // End progress display
            document.getElementById('college_progress').innerHTML = '';

            // Update the UI with college list
            displayCollegeList();

            // Close the Modal Dialog
            closeModal();
        });
    }
}


/**
 * Display Colleges
 */
function displayCollegeList() {

    // Use Async ajax call to get a list of colleges from the Client App
    $.when($.get('composer/client/getCollegeList')).done(function (_res) {

        // Successful response received, lets check it on browser console
        console.log(_res.college_list);

        let _str = '';
        let _nstr = '';

        // We will now build the Table to be displayed in UI
        _str += '<table><tr><th>Name</th><th>isApproved</th></tr>';
        _res.college_list.forEach(function (_row) {
            // Check is college is approved or NOT aaproved by university
            let td = (_row.is_approved == 0) ? '<td class="red"> NOT APPROVED</td>' 
                    : '<td class="green"> APPROVED</td>';

            _str += '<tr><td>' + '<a href="#" onClick=enrollProgram("' + _row.id + '")>' 
                    + _row.name + '</a></td>' + td + '</tr>';
            if (_row.is_approved == 0) {
                _nstr += '<input type="checkbox" name="collegeIds" value="' 
                    + _row.id + '">' + _row.name + '</input></br>';
            }
        })
        _str += '</table>';

        // Display College List
        document.getElementById('college_list').innerHTML = _str;
        document.getElementById('approve_list').innerHTML = _nstr;
    });
}



function submitApproveAffiliation() {
    let options = {};
    let arr = '';
    document.getElementById('approval_progress').innerHTML = '<img src="./icons/progress.gif"/>';
    $("input:checkbox[name=collegeIds]:checked").each(function () {
        let options = {};
        options.college_id = $(this).val();
        {
            $.when($.post('/composer/client/approveAffiliation', options)).done(function (_res) {
                document.getElementById('approval_progress').innerHTML = '';
                let val = _res.result;
                displayCollegeList();
                closeModal();
            });
        }
    });
}




function submitEnrollProgram() {
    document.getElementById('program_progress').innerHTML = '<img src="./icons/progress.gif"/>';
    let options = {};
    options.program_name = document.getElementById('program_name').value;
    options.college_id = collegeId;
    {
        $.when($.post('/composer/client/enrollProgram', options)).done(function (_res) {
            document.getElementById('program_progress').innerHTML = '';
            let val = _res.result;
            displayCollegeList();
            closeModal();
        });
    }
}

function submitGenerateCertificate() {
    let options = {};
    let arr = '';
    document.getElementById('certificate_progress').innerHTML = '<img src="./icons/progress.gif"/>';
    $("input:checkbox[name=gen_cer_student]:checked").each(function () {
        let options = {};
        options.student_id = $(this).val();
        {
            $.when($.post('/composer/client/issueCertificate', options)).done(function (_res) {
                document.getElementById('certificate_progress').innerHTML = '';
                let val = _res.result;
                displayStudentList();
                closeModal();
            });
        }
    });
}


function submitTakeAdmission() {
    var selected_program = $("input[name=program]:checked").val();
    if (selected_program == null) {
        alert('No Program Selected');
        return;
    }

    let student_name = document.getElementById('student_name').value;
    let student_dob = document.getElementById('student_dob').value;

    let studentDob = new Date(student_dob);
    if (studentDob == null) {
        alert('Incorrect Date Format');
        return;
    }

    let val = selected_program.split('##');
    let arr = '';
    document.getElementById('admission_progress').innerHTML = '<img src="./icons/progress.gif"/>';
    let options = {};
    options.student_name = student_name;
    options.student_dob = studentDob;
    options.college_name = val[0];
    options.program_name = val[1];
    {
        $.when($.post('/composer/client/takeAdmission', options)).done(function (_res) {
            document.getElementById('admission_progress').innerHTML = '';
            let val = _res.result;
            displayStudentList();
            closeModal();
        });
    }
}

/**
 * get History
 */
function getHistorian() {
    $.when($.get('fabric/getHistory')).done(function (_res) {
        let _str = '<h4> HyperLedger Transaction Blocks: ' + _res.result + '</h4>';
        if (_res.result === 'success') {
            _str += '<h3>Total Blocks: ' + _res.history.length + '</h3>';
            _str += '<table id="tt"><tr><th>Transaction Hash</th><th>Transaction Type</th><th>TimeStamp</th></tr>';
            _res.history.sort(function (a, b) { return (b.transactionTimestamp > a.transactionTimestamp) ? -1 : 1; });
            for (let each in _res.history) {
                (function (_idx, _arr) {
                    let _row = _arr[_idx];
                    _str += '<tr><td>' + _row.transactionId + '</td><td>' + _row.transactionType + '</td><td>' + _row.transactionTimestamp + '</td></tr>';
                })(each, _res.history);
            }
            _str += '</table>';
        }
        else { _str += formatMessage(_res.message); }
        document.getElementById('historian').innerHTML = _str;
    });
}

/**
 * Display Students
 */
function displayStudentList() {
    $.when($.get('composer/client/getStudentList')).done(function (_res) {
        console.log(_res.student_list);
        let _str = '';
        let _nstr = '';
        _str += '<table><tr><th>Name</th><th>Certificate ID</th></tr>';
        _res.student_list.forEach(function (_row) {
            let cid = (_row.certificateId == null) ? '...' : _row.certificateId;
            _str += '<tr><td>' + _row.name + '</td><td>' + cid + '</td></tr>';
        })
        _str += '</table>';
        document.getElementById('student_list').innerHTML = _str;
    });
}

let collegeId = null;
function enrollProgram(id) {
    collegeId = id;
    var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(500, 0.7);
    var modalBox = $(this).attr('data-modal-id');
    $('#' + 'enrollProgram').fadeIn($(this).data());
}

function approveAffiliation() {
    var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(500, 0.7);
    var modalBox = $(this).attr('data-modal-id');
    $('#' + 'approveAffiliation').fadeIn($(this).data());
}

function takeAdmission() {
    console.log('takeAdmission......');
    $.when($.get('composer/client/getCollegeList')).done(function (_res) {
        let _str = '';
        _str += '<table><tr><th>College</th><th>Programs</th></tr>';
        _res.college_list.forEach(function (_row) {
            if (_row.is_approved == 1) {
                let _pro_str = '<table>';
                _row.programs.forEach(function (_pro) {
                    _pro_str += '<tr><td><input type="radio" name="program" value="' + _row.name + '##' + _pro + '">' + _pro + '</input></td></tr>';
                })
                _str += '<tr class="mark"><td>' + _row.name + '</td><td>' + _pro_str + '</table></td>' + '</tr>';
            }
        })
        _str += '</table>';
        document.getElementById('admission_list').innerHTML = _str;
    });

    var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(500, 0.7);
    var modalBox = $(this).attr('data-modal-id');
    $('#' + 'takeAdmission').fadeIn($(this).data());
}


function generateCertificate() {
    console.log('generateCertificate......');
    $.when($.get('composer/client/getStudentList')).done(function (_res) {
        let _str = '';
        _str += '<table><tr><th>Select</th><th>Student ID</th><th>Student Name</th></tr>';
        _res.student_list.forEach(function (_row) {
            if (_row.certificateId == null) {
                _str += '<tr><td><input type="checkbox" name="gen_cer_student" value="' + _row.id + '"></input></td><td>' + _row.id + '</td><td>' + _row.name + '</td></tr>';
            }
        })
        _str += '</table>';
        document.getElementById('student_cer_list').innerHTML = _str;
    });

    var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(500, 0.7);
    var modalBox = $(this).attr('data-modal-id');
    $('#' + 'generateCertificate').fadeIn($(this).data());
}

function verifyCertificate() {
    let public_id = document.getElementById('verify_cer_id').value;
    if (public_id == '') {
        alert('Please Enter valid Public ID');
        return;
    }

    /*
        let options = { id: public_id };
        document.getElementById('verify_progress').innerHTML = '<img src="./icons/progress.gif"/>';
        $.when($.get('composer/client/getCertificateById', options)).done(function (_res) {
            console.log(res.certificates);
        });
    */

    document.getElementById('verify_progress').innerHTML = '<img src="./icons/progress.gif"/>';
    $.when($.get('composer/client/getStudentList')).done(function (_res) {
        let list = _res.student_list;
        var result = null;
        list.forEach(function (v) {
            console.log(v);
            if (v.certificateId == public_id) {
                result = v;
            }
        });
        console.log(result);

        if (result == null) {
            alert('Certificate Validation Failed - No such certificate found!');
            closeModal();
            return;
        }

        document.getElementById('_student_name_').innerHTML = result.name;
        document.getElementById('_program_name_').innerHTML = result.program;
        document.getElementById('_date_of_issue').innerHTML = Date().toString().split('2018')[0] + '2018';
        document.getElementById('__cer_id__').innerHTML = public_id;

        document.getElementById('verify_progress').innerHTML = '';
        closeModal();
        displayCertificate();
    });
}

function displayCertificate() {
    var appendthis = ("<div class='modal-overlay js-modal-close'></div>");
    $("body").append(appendthis);
    $(".modal-overlay").fadeTo(500, 0.7);
    var modalBox = $(this).attr('data-modal-id');
    $('#' + 'certificate').fadeIn($(this).data());
}

这主要是我的超级分类帐的工作代码。正如我所说的,错误是未定义NS_,但我清楚地检查了所有代码,发现我从未输入过错误的NS _

1 个答案:

答案 0 :(得分:0)

这对我有用(ps。应该反映参与者注册表的命名(“ stuRegistry”而不是“ assetRegistry”,但无论如何仍然有效)-不确定您是否提供了(根据上述错误msg判断)交易类中的命名空间?

仅供参考,我的命名空间定义为:

  ...

  var NS_UNIVERSITY   = 'org.gryphon.casestudy.university';
  var NS_COLLEGE      = 'org.gryphon.casestudy.college';
  var NS_STUDENT      = 'org.gryphon.casestudy.student';

  ...
    /**
         * Student can enroll them to a College and Program
         * @param {org.gryphon.casestudy.student.enrollStudent} args - student 
        details
         * @transaction
         */
        function enrollStudent(args) {
        return getParticipantRegistry(NS_STUDENT + '.Student')
            .then(function (stuRegistry) {
                var factory = getFactory();
                var studentId = 'Student-'  +   +  Date.parse(args.timestamp);  // removed this non deterministic code:  Date.now().toString();
                var student = factory.newResource(NS_STUDENT, 'Student', studentId);
                student.name = args.name;
                student.dob = args.dob;
                student.memberId = studentId; 
                student.programName = args.programName;
                student.collegeName = args.collegeName; 
                return stuRegistry.add(student)
                    .then(function (_res) {
                        return (_res);
                    }).catch(
                        function (error) {
                            return (error);
                        });
            });
        }

对于issueCertificate,下面是一个用async / await编写的示例,它更容易/更简单,并使用事务(argstimestamp字段确定性地生成您的ID(而不是new Date() ):

/**
    * Write your transcation processor functions here etc
    */
    var NS_UNIVERSITY   = 'org.gryphon.casestudy.university';
    var NS_COLLEGE      = 'org.gryphon.casestudy.college';
    var NS_STUDENT      = 'org.gryphon.casestudy.student';

    /**
     * create a new certificate entry
    * @param {org.gryphon.casestudy.university.issueCertificate} args - student details
     * @transaction
     */
   async  function issueCertificate(args) {

    // `Date.now().toString();` is non-deterministic
     var certificateId = 'CertificateID-' +  Date.parse(args.timestamp);

     var factory = getFactory();
     const  assetRegistry = await getAssetRegistry(NS_UNIVERSITY +  '.Certificate');

     const  certificate = factory.newResource(NS_UNIVERSITY, 'Certificate',  certificateId);
     certificate.issuedTo = args.studentName;
     certificate.programName = args.programName;
     certificate.issuedDate = new Date();
     certificate.certificateId = certificateId;

     await assetRegistry.add(certificate) ;

     const  participantRegistry = await getParticipantRegistry(NS_STUDENT + '.Student');

     const certifiedStudent =  await participantRegistry.get(args.studentID)

     certifiedStudent.certificateId = certificateId;

     var event = factory.newEvent(NS_UNIVERSITY,  'certificateIssuedEvent');            
     event.certificateId = certificateId;
     emit(event);  

     participantRegistry.update(certifiedStudent);
  }