github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/build-blockchain-insurance-app-master/web/www/blockchain/setup.js (about)

     1  'use strict';
     2  
     3  import config, { DEFAULT_CONTRACT_TYPES } from './config';
     4  import { OrganizationClient } from './utils';
     5  import http from 'http';
     6  import url from 'url';
     7  
     8  let status = 'down';
     9  let statusChangedCallbacks = [];
    10  
    11  // Setup clients per organization
    12  const insuranceClient = new OrganizationClient(
    13    config.channelName,
    14    config.orderer0,
    15    config.insuranceOrg.peer,
    16    config.insuranceOrg.ca,
    17    config.insuranceOrg.admin
    18  );
    19  const shopClient = new OrganizationClient(
    20    config.channelName,
    21    config.orderer0,
    22    config.shopOrg.peer,
    23    config.shopOrg.ca,
    24    config.shopOrg.admin
    25  );
    26  const repairShopClient = new OrganizationClient(
    27    config.channelName,
    28    config.orderer0,
    29    config.repairShopOrg.peer,
    30    config.repairShopOrg.ca,
    31    config.repairShopOrg.admin
    32  );
    33  const policeClient = new OrganizationClient(
    34    config.channelName,
    35    config.orderer0,
    36    config.policeOrg.peer,
    37    config.policeOrg.ca,
    38    config.policeOrg.admin
    39  );
    40  
    41  function setStatus(s) {
    42    status = s;
    43  
    44    setTimeout(() => {
    45      statusChangedCallbacks
    46        .filter(f => typeof f === 'function')
    47        .forEach(f => f(s));
    48    }, 1000);
    49  }
    50  
    51  export function subscribeStatus(cb) {
    52    if (typeof cb === 'function') {
    53      statusChangedCallbacks.push(cb);
    54    }
    55  }
    56  
    57  export function getStatus() {
    58    return status;
    59  }
    60  
    61  export function isReady() {
    62    return status === 'ready';
    63  }
    64  
    65  function getAdminOrgs() {
    66    return Promise.all([
    67      insuranceClient.getOrgAdmin(),
    68      shopClient.getOrgAdmin(),
    69      repairShopClient.getOrgAdmin(),
    70      policeClient.getOrgAdmin()
    71    ]);
    72  }
    73  
    74  (async () => {
    75    // Login
    76    try {
    77      await Promise.all([
    78        insuranceClient.login(),
    79        shopClient.login(),
    80        repairShopClient.login(),
    81        policeClient.login()
    82      ]);
    83    } catch (e) {
    84      console.log('Fatal error logging into blockchain organization clients!');
    85      console.log(e);
    86      process.exit(-1);
    87    }
    88    // Setup event hubs
    89    insuranceClient.initEventHubs();
    90    shopClient.initEventHubs();
    91    repairShopClient.initEventHubs();
    92    policeClient.initEventHubs();
    93  
    94    // Bootstrap blockchain network
    95    try {
    96      await getAdminOrgs();
    97      if (!(await insuranceClient.checkChannelMembership())) {
    98        console.log('Default channel not found, attempting creation...');
    99        const createChannelResponse =
   100          await insuranceClient.createChannel(config.channelConfig);
   101        if (createChannelResponse.status === 'SUCCESS') {
   102          console.log('Successfully created a new default channel.');
   103          console.log('Joining peers to the default channel.');
   104          await Promise.all([
   105            insuranceClient.joinChannel(),
   106            shopClient.joinChannel(),
   107            repairShopClient.joinChannel(),
   108            policeClient.joinChannel()
   109          ]);
   110          // Wait for 10s for the peers to join the newly created channel
   111          await new Promise(resolve => {
   112            setTimeout(resolve, 10000);
   113          });
   114        }
   115      }
   116    } catch (e) {
   117      console.log('Fatal error bootstrapping the blockchain network!');
   118      console.log(e);
   119      process.exit(-1);
   120    }
   121  
   122    // Initialize network
   123    try {
   124      await Promise.all([
   125        insuranceClient.initialize(),
   126        shopClient.initialize(),
   127        repairShopClient.initialize(),
   128        policeClient.initialize()
   129      ]);
   130    } catch (e) {
   131      console.log('Fatal error initializing blockchain organization clients!');
   132      console.log(e);
   133      process.exit(-1);
   134    }
   135  
   136    // Install chaincode on all peers
   137    let installedOnInsuranceOrg, installedOnShopOrg, installedOnRepairShopOrg,
   138      installedOnPoliceOrg;
   139    try {
   140      await getAdminOrgs();
   141      installedOnInsuranceOrg = await insuranceClient.checkInstalled(
   142        config.chaincodeId, config.chaincodeVersion, config.chaincodePath);
   143      installedOnShopOrg = await shopClient.checkInstalled(
   144        config.chaincodeId, config.chaincodeVersion, config.chaincodePath);
   145      installedOnRepairShopOrg = await repairShopClient.checkInstalled(
   146        config.chaincodeId, config.chaincodeVersion, config.chaincodePath);
   147      installedOnPoliceOrg = await policeClient.checkInstalled(
   148        config.chaincodeId, config.chaincodeVersion, config.chaincodePath);
   149    } catch (e) {
   150      console.log('Fatal error getting installation status of the chaincode!');
   151      console.log(e);
   152      process.exit(-1);
   153    }
   154  
   155    if (!(installedOnInsuranceOrg && installedOnShopOrg &&
   156      installedOnRepairShopOrg && installedOnPoliceOrg)) {
   157      console.log('Chaincode is not installed, attempting installation...');
   158  
   159      // Pull chaincode environment base image
   160      try {
   161        await getAdminOrgs();
   162        const socketPath = process.env.DOCKER_SOCKET_PATH ||
   163        (process.platform === 'win32' ? '//./pipe/docker_engine' : '/var/run/docker.sock');
   164        const ccenvImage = process.env.DOCKER_CCENV_IMAGE ||
   165          'hyperledger/fabric-ccenv:x86_64-1.1.0';
   166        const listOpts = { socketPath, method: 'GET', path: '/images/json' };
   167        const pullOpts = {
   168          socketPath, method: 'POST',
   169          path: url.format({ pathname: '/images/create', query: { fromImage: ccenvImage } })
   170        };
   171  
   172        const images = await new Promise((resolve, reject) => {
   173          const req = http.request(listOpts, (response) => {
   174            let data = '';
   175            response.setEncoding('utf-8');
   176            response.on('data', chunk => { data += chunk; });
   177            response.on('end', () => { resolve(JSON.parse(data)); });
   178          });
   179          req.on('error', reject); req.end();
   180        });
   181  
   182        const imageExists = images.some(
   183          i => i.RepoTags && i.RepoTags.some(tag => tag === ccenvImage));
   184        if (!imageExists) {
   185          console.log(
   186            'Base container image not present, pulling from Docker Hub...');
   187          await new Promise((resolve, reject) => {
   188            const req = http.request(pullOpts, (response) => {
   189              response.on('data', () => { });
   190              response.on('end', () => { resolve(); });
   191            });
   192            req.on('error', reject); req.end();
   193          });
   194          console.log('Base container image downloaded.');
   195        } else {
   196          console.log('Base container image present.');
   197        }
   198      } catch (e) {
   199        console.log('Fatal error pulling docker images.');
   200        console.log(e);
   201        process.exit(-1);
   202      }
   203  
   204      // Install chaincode
   205      const installationPromises = [
   206        insuranceClient.install(
   207          config.chaincodeId, config.chaincodeVersion, config.chaincodePath),
   208        shopClient.install(
   209          config.chaincodeId, config.chaincodeVersion, config.chaincodePath),
   210        repairShopClient.install(
   211          config.chaincodeId, config.chaincodeVersion, config.chaincodePath),
   212        policeClient.install(
   213          config.chaincodeId, config.chaincodeVersion, config.chaincodePath)
   214      ];
   215      try {
   216        await Promise.all(installationPromises);
   217        await new Promise(resolve => {   setTimeout(resolve, 10000); });
   218        console.log('Successfully installed chaincode on the default channel.');
   219      } catch (e) {
   220        console.log('Fatal error installing chaincode on the default channel!');
   221        console.log(e);
   222        process.exit(-1);
   223      }
   224  
   225      // Instantiate chaincode on all peers
   226      // Instantiating the chaincode on a single peer should be enough (for now)
   227      try {
   228        // Initial contract types
   229        await insuranceClient.instantiate(config.chaincodeId,
   230          config.chaincodeVersion, DEFAULT_CONTRACT_TYPES);
   231        console.log('Successfully instantiated chaincode on all peers.');
   232        setStatus('ready');
   233      } catch (e) {
   234        console.log('Fatal error instantiating chaincode on some(all) peers!');
   235        console.log(e);
   236        process.exit(-1);
   237      }
   238    } else {
   239      console.log('Chaincode already installed on the blockchain network.');
   240      setStatus('ready');
   241    }
   242  })();
   243  
   244  // Export organization clients
   245  export {
   246    insuranceClient,
   247    shopClient,
   248    repairShopClient,
   249    policeClient
   250  };