---
# System prepended metadata

title: Untitled

---



## script

````

const rpc = require("./utils/rpc");
const model = require("./models/blocks.model");


let block;

const start = async () => {

  // SYNCRONIZE THE BLOCKCHAIN


  // 1. Récupérer le dernier bloc enregistré en base de données
  let dbBlock  = await model.getCurrent();

  let lastHash;
  if(dbBlock === null) {
    // Genesis block
    lastHash = "000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"
  } else {
    lastHash = dbBlock.hash;
  }

  // Genesis block
  if(dbBlock === null) {
    block = await rpc.call({
      jsonrpc: "1.0",
      method: "getblock",
      id: "curltext",
      params: [lastHash],
    });
    // coinbasevalue 
    block.coinbasevalue = 50.00000000;
    await model.saveBlock(block);
  } else {
    block = await rpc.call({
      jsonrpc: "1.0",
      method: "getblock",
      id: "curltext",
      params: [lastHash],
    });
  }


  // 2. Récupérer les dernier bloc connus
  while (block.nextblockhash !== undefined) {
    block = await registerBlock(block.nextblockhash);
    lastHash = block.hash;
  }

  // PULL 1S BLOCKCHAIN

  // 3. Une fois la syncro terminée, on récupère le dernier bloc connu chaque minute. Si le dernier block contient block.nextblockhash !== undefined

  setInterval(async () => {
    block = await rpc.call({
      jsonrpc: "1.0",
      method: "getblock",
      id: "curltext",
      params: [lastHash],
    });

    // Si on a une autre TX à dépiler 
    if(block.nextblockhash !== undefined) {
      while (block.nextblockhash !== undefined) {
        block = await registerBlock(block.nextblockhash);
      }
    } else {
      // Si on a une seule TX à dépiler, vérifier qu'on l'a pas déjà faite
      let dbBlock  = await model.getCurrent();

      if(dbBlock.hash === block.previousblockhash) {
        console.log('New height')
        block = await registerBlock(block.nextblockhash);
      }
    }
  }, 1000);


}


const registerBlock = async(blockhash) => {
  // Get the bloc
  block = await rpc.call({
    jsonrpc: "1.0",
    method: "getblock",
    id: "curltext",
    params: [blockhash,2],
  });

  // If TX is not empty 
  if(block.tx.length !== 0) {
    block.coinbasevalue = block.tx[0].vout.reduce((partialSum, vout) => partialSum + vout.value, 0)
  }

  // Add a YYYY-MM-DD date
  block.date = new Date(block.time*1000).toISOString().split('T')[0];


  // save the block
  await model.saveBlock(block);

  return block;
}
start()


````