使用 SDK 在结构中进行用户注册时出错

Getting error while doing users registration in fabric using SDK

我正在尝试一次注册多个用户,但是在执行时出现错误

"error: [FabricCAClientService.js]: Failed to enroll 0006, error:%o message=Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]], stack=Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]
    at IncomingMessage.response.on (/vagrant/Dfarm-app/node/node_modules/fabric-ca-client/lib/FabricCAClient.js:470:22)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)
Failed to register user: Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]"

我正在尝试与一个用户一起实现它 运行 很好,我们正在尝试与多个用户一起实现它给出的错误。

任何人都可以建议我如何在区块链中注册多个用户。

请参阅下面的 registerUser.js 文件

'use strict';

const { FileSystemWallet, Gateway, X509WalletMixin } = require('fabric-network');
const fs = require('fs');
const path = require('path');

// capture network variables from config.json
// var configPath = path.join(process.cwd(), 'config.json');
// const configJSON = fs.readFileSync(configPath, 'utf8');
var configJSON = fs.readFileSync('config.json');

var config = JSON.parse(configJSON);
var connection_file = config.connection_file;
var appAdmin = config.appAdmin;
var orgMSPID = config.orgMSPID;
var userName = config.userName;
var gatewayDiscovery = config.gatewayDiscovery;

const ccpPath = path.join(process.cwd(), connection_file);
const ccpJSON = fs.readFileSync(ccpPath, 'utf8');
const ccp = JSON.parse(ccpJSON);

async function main() {
    try {

         var userDetails = config.userDetails;
        //  console.log('test', userDetails)
        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');


        const wallet = new FileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);
        // Check to see if we've already enrolled the user.
        for(var i=0; i< userDetails.length;i++){   
            // console.log('test',walletPath)

        let userExists = await wallet.exists(userDetails[i].userName);
        if (userExists) {
            //    console.log('test',userDetails[0].userName)
            console.log(`An identity for the user ${userDetails[i].userName} already exists in the wallet`);
            return;
        }
    }
            // console.log('test',walletPath)

        // Check to see if we've already enrolled the admin user.
        const adminExists = await wallet.exists(appAdmin);
        if (!adminExists) {

            console.log(`An identity for the admin user ${appAdmin} does not exist in the wallet`);
            console.log('Run the enrollAdmin.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: appAdmin, discovery: gatewayDiscovery });

        // Get the CA client object from the gateway for interacting with the CA.
        const ca = gateway.getClient().getCertificateAuthority();
        const adminIdentity = gateway.getCurrentIdentity();

        // Register the user, enroll the user, and import the new identity into the wallet.
        for(var i=0; i< userDetails.length;i++){     
        var secret = await ca.register({ enrollmentID:userDetails[i].enrollmentID,userName:userDetails[i].userName, role:userDetails[i].role }, adminIdentity);
        var enrollment = await ca.enroll({ enrollmentID:userDetails[i].enrollmentID, enrollmentSecret: userDetails[i].enrollmentSecret });
        var userIdentity = X509WalletMixin.createIdentity(orgMSPID, enrollment.certificate, enrollment.key.toBytes());
        wallet.import(userDetails[i].userName, userIdentity);
        console.log('Successfully registered and enrolled admin user ' + userDetails[i].userName + ' and imported it into the wallet');
        }
    } catch (error) {
        console.error(`Failed to register user: ${error}`);
        process.exit(1);
    }
}

main();

config.json 文件

{
   "connection_file": "connection.json",
   "appAdmin": "admin",
   "appAdminSecret": "adminpw",
   "orgMSPID": "DfarmadminMSP",
   "caName": "ca.dfarmadmin.com",
   "userDetails": [{"username":"user1","enrollmentID":"0006","role":"client","enrollmentSecret": "1234"},
   {"username":"user2", "enrollmentID":"0002","role":"client","enrollmentSecret": "abcs" },
   {"username":"user3", "enrollmentID":"0003","role":"client","enrollmentSecret": "9807" },
   {"username":"user4","enrollmentID":"0004","role":"client","enrollmentSecret": "abcd" }
   ],

   "gatewayDiscovery": { "enabled": false }
}

connection.json 文件

{
    "name": "basic-network",
    "version": "1.0.0",
    "client": {
        "tlsEnable": false,
        "adminUser": "admin",
        "adminPassword": "adminpw",
        "enableAuthentication": false,
        "organization": "dfarmadmin",
        "connection": {
            "timeout": {
                "peer": {
                    "endorser": "300"
                },
                "orderer": "300"
            }
        }
    },
    "channels": {
        "dfarmchannel": {
            "orderers": [
                "orderer.dfarmadmin.com"
            ],
            "peers": {
                "peer0.dfarmadmin.com": {
                    "endorsingPeer": true,
                    "chaincodeQuery": true,
                    "ledgerQuery": true,
                    "eventSource": true
                },

                "connection": {
                    "timeout": {
                        "peer": {
                            "endorser": "6000",
                            "eventHub": "6000",
                            "eventReg": "6000"
                        }
                    }
                },
                "peer0.dfarmretail.com": {
                    "endorsingPeer": false,
                    "chaincodeQuery": true,
                    "ledgerQuery": true,
                    "eventSource": false
                }
            }
        }
    },
    "organizations": {
        "dfarmadmin": {
            "mspid": "DfarmadminMSP",
            "peers": [
                "peer0.dfarmadmin.com"
            ],
            "certificateAuthorities": [
                "ca.dfarmadmin.com"
            ]
        },
        "dfarmretail": {
            "mspid": "DfarmretailMSP",
            "peers": [
                "peer0.dfarmretail.com"
            ],
            "certificateAuthorities": [
                "ca.dfarmadmin.com"
            ]
        }
    },
    "orderers": {
        "orderer.dfarmadmin.com": {
            "url": "grpc://localhost:7050",
            "eventUrl": "grpc://localhost:7053"

        }
    },
    "peers": {
        "peer0.dfarmadmin.com": {
            "url": "grpc://localhost:7051"
        },
        "peer0.dfarmretail.com": {
            "url": "grpc://localhost:8051"
        }
    },
    "certificateAuthorities": {
        "ca.dfarmadmin.com": {
            "url": "http://localhost:7054",
            "caName": "ca.dfarmadmin.com"
        }
    }
}

AdminIdentiy 控制台

adminIdentity User {
  _name: 'admin',
  _roles: null,
  _affiliation: '',
  _enrollmentSecret: '',
  _identity: 
   Identity {
     _certificate: '-----BEGIN CERTIFICATE-----\nMIIB/jCCAaSgAwIBAgIUdrt0WjnSmGsX1WuBWvXVTizqFKUwCgYIKoZIzj0EAwIw\nbzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xFzAVBgNVBAoTDmRmYXJtYWRtaW4uY29tMRowGAYDVQQDExFj\nYS5kZmFybWFkbWluLmNvbTAeFw0xOTA4MTQxMTEyMDBaFw0yMDA4MTMxMTE3MDBa\nMCExDzANBgNVBAsTBmNsaWVudDEOMAwGA1UEAxMFYWRtaW4wWTATBgcqhkjOPQIB\nBggqhkjOPQMBBwNCAARXptenPPGpVnJsEFv0wmJeybDYNoClJCyAv3GcRPb04WLR\nAynEoSXf+jwYIjypV98oeR127haGcDo7jHUn0DnBo2wwajAOBgNVHQ8BAf8EBAMC\nB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUW1YmLO6OaZB7FwXv6Gu7yc9jhNMw\nKwYDVR0jBCQwIoAgeD1bXE22u42++Y2v96xX+EKLzk8JkEcheGl5g8XGRkkwCgYI\nKoZIzj0EAwIDSAAwRQIhALluXWayFpylTOLCDIp925yn0rrtl77D/rM8AkOksTsE\nAiAEQ+w5pElSLFBINH/c0N1CgGN1snsdK1LRkUNjCk29Fg==\n-----END CERTIFICATE-----\n',
     _publicKey: ECDSA_KEY { _key: [Object] },
     _mspId: 'DfarmadminMSP',
     _cryptoSuite: 
      CryptoSuite_ECDSA_AES {
        _keySize: 256,
        _hashAlgo: 'SHA2',
        _cryptoKeyStore: [Object],
        _curveName: 'secp256r1',
        _ecdsaCurve: [Object],
        _hashFunction: [Function],
        _hashOutputSize: 32,
        _ecdsa: [Object] } },
  _signingIdentity: 
   SigningIdentity {
     _certificate: '-----BEGIN CERTIFICATE-----\nMIIB/jCCAaSgAwIBAgIUdrt0WjnSmGsX1WuBWvXVTizqFKUwCgYIKoZIzj0EAwIw\nbzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDVNh\nbiBGcmFuY2lzY28xFzAVBgNVBAoTDmRmYXJtYWRtaW4uY29tMRowGAYDVQQDExFj\nYS5kZmFybWFkbWluLmNvbTAeFw0xOTA4MTQxMTEyMDBaFw0yMDA4MTMxMTE3MDBa\nMCExDzANBgNVBAsTBmNsaWVudDEOMAwGA1UEAxMFYWRtaW4wWTATBgcqhkjOPQIB\nBggqhkjOPQMBBwNCAARXptenPPGpVnJsEFv0wmJeybDYNoClJCyAv3GcRPb04WLR\nAynEoSXf+jwYIjypV98oeR127haGcDo7jHUn0DnBo2wwajAOBgNVHQ8BAf8EBAMC\nB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUW1YmLO6OaZB7FwXv6Gu7yc9jhNMw\nKwYDVR0jBCQwIoAgeD1bXE22u42++Y2v96xX+EKLzk8JkEcheGl5g8XGRkkwCgYI\nKoZIzj0EAwIDSAAwRQIhALluXWayFpylTOLCDIp925yn0rrtl77D/rM8AkOksTsE\nAiAEQ+w5pElSLFBINH/c0N1CgGN1snsdK1LRkUNjCk29Fg==\n-----END CERTIFICATE-----\n',
     _publicKey: ECDSA_KEY { _key: [Object] },
     _mspId: 'DfarmadminMSP',
     _cryptoSuite: 
      CryptoSuite_ECDSA_AES {
        _keySize: 256,
        _hashAlgo: 'SHA2',
        _cryptoKeyStore: [Object],
        _curveName: 'secp256r1',
        _ecdsaCurve: [Object],
        _hashFunction: [Function],
        _hashOutputSize: 32,
        _ecdsa: [Object] },
     _signer: Signer { _cryptoSuite: [Object], _key: [Object] } },
  _mspId: 'DfarmadminMSP',
  _cryptoSuite: 
   CryptoSuite_ECDSA_AES {
     _keySize: 256,
     _hashAlgo: 'SHA2',
     _cryptoKeyStore: 
      CryptoKeyStore {
        logger: [Object],
        _store: [Object],
        _storeConfig: [Object],
        _getKeyStore: [Function] },
     _curveName: 'secp256r1',
     _ecdsaCurve: 
      PresetCurve {
        curve: [Object],
        g: <EC Point x: 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 y: 4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5>,
        n: <BN: ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551>,
        hash: [Object] },
     _hashFunction: [Function],
     _hashOutputSize: 32,
     _ecdsa: 
      EC {
        curve: [Object],
        n: <BN: ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551>,
        nh: <BN: 7fffffff800000007fffffffffffffffde737d56d38bcf4279dce5617e3192a8>,
        g: <EC Point x: 6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296 y: 4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5>,
        hash: [Object] } } }
2019-08-14T11:17:28.526Z - error: [FabricCAClientService.js]: Failed to enroll 005, error:%o message=Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]], stack=Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]
    at IncomingMessage.response.on (/vagrant/Dfarm-app/Node/node_modules/fabric-ca-client/lib/FabricCAClient.js:470:22)
    at emitNone (events.js:111:20)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:139:11)
    at process._tickCallback (internal/process/next_tick.js:181:9)
Failed to register user: Error: Enrollment failed with errors [[{"code":20,"message":"Authentication failure"}]]

我怀疑问题是因为您有编码错误(或 JSON 中的错误 :-))。该代码正在寻找元素中的 userName 字段,但您的 JSON 数组有一个字段 username (lc)。您可以轻松更改 JSON 以匹配。

错误:身份验证失败

很明显您提供了错误的凭据,这意味着错误的秘密

对于注册,我们需要 ID 和 Secret

仔细检查密码并确保您已注册,然后再继续注册

如果一个用户要多次注册,您需要在ca.register的json中指定maxEnrollments。否则,ca.enroll会提示{ code: 20, message: 'Authentication failure'}

例如,对于注册,您可能有

var secret = await ca.register({
  enrollmentID: userDetails[i].enrollmentID,
  userName: userDetails[i].userName,
  role: userDetails[i].role,
  maxEnrollments: -1 // -1 means no limit on number of enrollments after registration
}, adminIdentity);