How to use the fabric-network.Gateway function in fabric-network

To help you get started, we’ve selected a few fabric-network examples, based on popular ways it is used in public projects.

github hyperledger-labs / blockchain-analyzer / apps / dummyapp / queryAll.js View on Github external
// 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.
        const userExists = await wallet.exists('user1');
        if (!userExists) {
            console.log('An identity for the user "user1" does not exist in the wallet');
            console.log('Run the registerUser.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: 'user1', discovery: { enabled: false } });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork(config.channel.channelName);

        // Get the contract from the network.
        const contract = network.getContract(config.channel.contract);

        // Evaluate the specified transaction.
        console.log('No key provided, querying all values')
        const result = await contract.evaluateTransaction('queryAllValues');
        console.log(`Transaction has been evaluated, result is: ${result.toString()}`);

    } catch (error) {
        console.error(`Failed to evaluate transaction: ${error}`);
        process.exit(1);
github johnwalicki / IoT-AssetTracking-Perishable-Network-Blockchain / Blockchain / web-app / server / registerUser.js View on Github external
const userExists = await wallet.exists(userName);
        if (userExists) {
            console.log('An identity for the user "user1" already exists in the wallet');
            return;
        }

        // 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 "admin" 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.
        const secret = await ca.register({ affiliation: 'org1.department1', enrollmentID: userName, role: 'client' }, adminIdentity);
        const enrollment = await ca.enroll({ enrollmentID: userName, enrollmentSecret: secret });
        const userIdentity = X509WalletMixin.createIdentity(orgMSPID, enrollment.certificate, enrollment.key.toBytes());
        wallet.import(userName, userIdentity);
        console.log('Successfully registered and enrolled user ' + userName + ' and imported it into the wallet');

    } catch (error) {
        console.error(`Failed to register user ${userName} : ${error}`);
        process.exit(1);
github IBM / auction-events / application / application.js View on Github external
async function main(){

    // A gateway defines the peers used to access Fabric networks
    const gateway = new Gateway();

    // Main try/catch block
    try {

        // A gateway defines the peers used to access Fabric networks
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: appAdmin , discovery: {enabled: true, asLocalhost:false }});
 
        console.log('Connected to Fabric gateway.');

        // Get addressability to network
        const network = await gateway.getNetwork(channelName);

        console.log('Got addressability to network');

        // Get addressability to  contract
github IBM / auction-events / application / blockEvents.js View on Github external
try {

    let response;

    // Check to see if we've already enrolled the user.
    const userExists = await wallet.exists(peerIdentity);
    if (!userExists) {
      console.log('An identity for the user ' + peerIdentity + ' does not exist in the wallet');
      console.log('Run the registerUser.js application before retrying');
      response.error = 'An identity for the user ' + peerIdentity + ' does not exist in the wallet. Register ' + peerIdentity + ' first';
      return response;
    }

    //connect to Fabric Network, but starting a new gateway
    const gateway = new Gateway();

    //use our config file, our peerIdentity, and our discovery options to connect to Fabric network.
    await gateway.connect(connectionProfile, {wallet, identity: peerIdentity, discovery: config.gatewayDiscovery});
    console.log('gateway connect');

    //connect to our channel that has been created on IBM Blockchain Platform
    const network = await gateway.getNetwork('mychannel');

    //our block listener is listening to our channel, and seeing if any blocks are added to our channel
    await network.addBlockListener('block-listener', (err, block) => {
      if (err) {
        console.log(err);
        return;
      }

      console.log('*************** start block header **********************')
github hyperledger-labs / blockchain-analyzer / apps / dummyapp / invoke.js View on Github external
// Check to see if we've already enrolled all the users.
        for (let i = 0; i < config.users.length; i++) {
            var userExists = await wallet.exists(config.users[i].name);
            if (!userExists) {
                console.log('An identity for the user does not exist in the wallet: ', config.users[i].name);
                console.log('Run the registerUser.js application before retrying');
                return;
            }
        }

        for (let i = 0; i < config.transactions.length; i++) {

            let tx = config.transactions[i];
            // Create a new gateway for connecting to our peer node.
            const gateway = new Gateway();
            await gateway.connect(ccp, { wallet, identity: tx.user, discovery: { enabled: false } });

            // Get the network (channel) our contract is deployed to.
            const network = await gateway.getNetwork(config.channel.channelName);

            // Get the contract from the network.
            const contract = network.getContract(config.channel.contract);

            // Submit the transaction.
            if (tx.key){
                if (tx.previousKey) {
                    await contract.submitTransaction(tx.txFunction, tx.key, tx.previousKey);
                    console.log(`Transaction has been submitted: ${tx.user}\t${tx.txFunction}\t${tx.key}\t${tx.previousKey}`);
                }
                else {
                    await contract.submitTransaction(tx.txFunction, tx.key);
github IBM / decentralized-energy-fabric-on-IBP20 / application / invoker-tx / cash-trade.js View on Github external
// Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), '..', '_idwallet');
        const wallet = new FileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const userExists = await wallet.exists(participantId);
        if (!userExists) {
            console.log(`An identity for the user "${participantId}" does not exist in the wallet`);
            console.log('Run the registerUser.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: participantId, discovery: gatewayDiscovery });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork('mychannel');

        // Get the contract from the network.
        const contract = network.getContract('decentralizedenergy');
        console.log('\nSubmit CashTrade transaction.');
        var cashRate = "1";
        var cashValue = "10";
        var cashReceiverId = bankId;
        var cashSenderId = residentId;

        const cashTradeResponse = await contract.submitTransaction('CashTrade', cashRate, cashValue, cashReceiverId, cashSenderId);
        // console.log('cashTradeResponse: ')
        // console.log(cashTradeResponse.toString('utf8'));
github IBM / assetTracking / org1 / application / invoke.js View on Github external
async function main() {

  // A gateway defines the peers used to access Fabric networks
  const gateway = new Gateway();

  // Main try/catch block
  try {

    // Set connection options; identity and wallet
    let connectionOptions = {
      identity: "admin",
      wallet: wallet,
      discovery: { enabled:false, asLocalhost: true }
    };

    await gateway.connect(connectionProfile, connectionOptions);

    // Access PaperNet network
    console.log('Use network channel: mychannel.');
github hyperledger / caliper / packages / caliper-fabric / lib / fabric.js View on Github external
wallet: this.wallet,
            identity: userId,
            discovery: {
                asLocalhost: this.configLocalHost,
                enabled: this.configDiscovery
            },
            eventHandlerOptions: { commitTimeout: this.configDefaultTimeout }
        };

        // Optional on mutual auth
        if (this.networkUtil.isMutualTlsEnabled()) {
            opts.clientTlsIdentity = userId;
        }

        // Retrieve gateway using ccp and options
        const gateway = new FabricNetworkAPI.Gateway();

        logger.info(`Connecting user ${userId} to a Network Gateway`);
        await gateway.connect(this.networkUtil.getNetworkObject(), opts);

        // return the gateway object
        return gateway;
    }
github IBM-Blockchain / vehicle-manufacture / apps / rest_server / src / fabricproxy.ts View on Github external
private async setupGateway(user: string): Promise<Gateway> {
        try {
            const gateway = new Gateway();
            // Set connection options; use 'admin' identity from application wallet
            const connectionOptions = {
                discovery: {enabled: false},
                identity: user,
                wallet: this.wallet,
            };

            // Connect to gateway using application specified parameters
            await gateway.connect(this.ccp, connectionOptions);
            return gateway;
        } catch (error) {
            throw error;
        }
    }
}
github hyperledger / fabric-test / feature / sdk / node / invoke.js View on Github external
async function _submitTransaction(org, chaincode, network_config){
    const ccp = network_config['common-connection-profile'];
    const orgConfig = ccp.organizations[org];
    const cert = common.readAllFiles(orgConfig.signedCertPEM)[0];
    const key = common.readAllFiles(orgConfig.adminPrivateKeyPEM)[0];
    const inMemoryWallet = new InMemoryWallet();

    const gateway = new Gateway();

    try {
        await inMemoryWallet.import('admin', X509WalletMixin.createIdentity(orgConfig.mspid, cert, key));

        const opts = {
            wallet: inMemoryWallet,
            identity: 'admin',
            discovery: { enabled: false }
        };

        await gateway.connect(ccp, opts);

        const network = await gateway.getNetwork(chaincode.channelId)
        const contract = await network.getContract(chaincode.chaincodeId);

        const args = [chaincode.fcn, ...chaincode.args];