github.com/muhammedhassanm/blockchain@v0.0.0-20200120143007-697261defd4d/sawtooth-supply-chain-master/ledger_sync/db/blocks.js (about)

     1  /**
     2   * Copyright 2018 Intel Corporation
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   * ----------------------------------------------------------------------------
    16   */
    17  'use strict'
    18  
    19  const r = require('rethinkdb')
    20  const db = require('./')
    21  
    22  const stateTables = [
    23    'agents',
    24    'records',
    25    'recordTypes',
    26    'properties',
    27    'propertyPages',
    28    'proposals'
    29  ]
    30  
    31  const getForkedDocRemover = blockNum => tableName => {
    32    return db.modifyTable(tableName, table => {
    33      return table
    34        .filter(r.row('startBlockNum').ge(blockNum))
    35        .delete()
    36        .do(() => table.filter(doc => doc('endBlockNum').ge(blockNum)))
    37        .update({endBlockNum: Number.MAX_SAFE_INTEGER})
    38    })
    39  }
    40  
    41  const resolveFork = block => {
    42    const defork = getForkedDocRemover(block.blockNum)
    43    return db.modifyTable('blocks', blocks => {
    44      return blocks
    45        .filter(r.row('blockNum').ge(block.blockNum))
    46        .delete()
    47        .do(() => blocks.insert(block))
    48    })
    49      .then(() => Promise.all(stateTables.map(tableName => defork(tableName))))
    50      .then(() => block)
    51  }
    52  
    53  const insert = block => {
    54    return db.modifyTable('blocks', blocks => {
    55      return blocks
    56        .get(block.blockNum)
    57        .do(foundBlock => {
    58          return r.branch(foundBlock, foundBlock, blocks.insert(block))
    59        })
    60    })
    61      .then(result => {
    62        // If the blockNum did not already exist, or had the same id
    63        // there is no fork, return the block
    64        if (!result.blockId || result.blockId === block.blockId) {
    65          return block
    66        }
    67        return resolveFork(block)
    68      })
    69  }
    70  
    71  module.exports = {
    72    insert
    73  }