Upgrades a single snapshot by adding the blockhash to it and to any pending transactions
181047
def _transform_snapshot(
        raw_snapshot: str,
        storage: SQLiteStorage,
        cache: BlockHashCache,
) -> str:
    """"""
    snapshot = json.loads(raw_snapshot)
    block_number = int(snapshot['block_number'])
    snapshot['block_hash'] = cache.get(block_number)

    pending_transactions = snapshot['pending_transactions']
    new_pending_transactions = []
    for transaction_data in pending_transactions:
        if 'raiden.transfer.events.ContractSend' not in transaction_data['_type']:
            raise InvalidDBData(
                "Error during v18 -> v19 upgrade. Chain state's pending transactions "
                "should only contain ContractSend transactions",
            )

        # For each pending transaction find the corresponding DB event record.
        event_record = storage.get_latest_event_by_data_field(
            filters=transaction_data,
        )
        if not event_record.data:
            raise InvalidDBData(
                'Error during v18 -> v19 upgrade. Could not find a database event '
                'table entry for a pending transaction.',
            )

        event_record_data = json.loads(event_record.data)
        transaction_data['triggered_by_block_hash'] = event_record_data['triggered_by_block_hash']
        new_pending_transactions.append(transaction_data)

    snapshot['pending_transactions'] = new_pending_transactions
    return json.dumps(snapshot)
837973
def atomic_update(clazz, updates = {})
      @adds += updates.keys.length
      indexer.add_atomic_update(clazz, updates)
    end
155081
def refresh(self):
        
        data = self.machine.raw_snapshot_data(self.name)
        self._save(data)
327385
def commit(self, snapshot: Tuple[Hash32, UUID]) -> None:
        
        _, account_snapshot = snapshot
        self._account_db.commit(account_snapshot)
631061
def snapshot(*args)
      sn = Snapshot.new self, *args
      if block_given?
        begin
          yield sn
        ensure
          sn.release
        end
      else
        sn
      end
    end
594093
def commit(self):
        """"""
        if (not self._add_cache and
                not self._remove_cache and
                not self._undefined_cache):
            return

        for store_key, hash_values in self._add_cache.items():
            for hash_value in hash_values:
                super(TransactionalIndex, self).add_hashed_value(
                    hash_value, store_key)
        for store_key in self._remove_cache:
            super(TransactionalIndex, self).remove_key(store_key)
        for store_key in self._undefined_cache:
            super(TransactionalIndex, self).add_undefined(store_key)
        if not self.ephemeral:
            self.save_to_store()

        self._init_cache()
        self._in_transaction = True
596014
def _update(collection_name, upsert, multi, spec, doc, check_keys, opts):
    """"""
    flags = 0
    if upsert:
        flags += 1
    if multi:
        flags += 2
    encode = _dict_to_bson  # Make local. Uses extensions.
    encoded_update = encode(doc, check_keys, opts)
    return b"".join([
        _ZERO_32,
        _make_c_string(collection_name),
        _pack_int(flags),
        encode(spec, False, opts),
        encoded_update]), len(encoded_update)
710270
def update_snapshots(self, snapshots_data: List[Tuple[str, int]]):
        
        cursor = self.conn.cursor()
        cursor.executemany(
            'UPDATE state_snapshot SET data=? WHERE identifier=?',
            snapshots_data,
        )
        self.maybe_commit()
435330
function addIdToSnapshot(snapshot) {
  var record = snapshot.record;
  record.get('store').updateId(record, { id: generateUniqueId() });
  return record._createSnapshot();
}
894791
function update () {
      sourceOrOptions.bundle()
        .pipe(concat(function (data) {
          add(filepath, data.toString())
        }))
        .on('error', function (err) {
          console.error(err.stack)
          ASSET_PENDING--
        })
    }
600706
function(transaction, results) {
    if (ydn.db.core.req.CachedWebsqlCursor.DEBUG) {
      goog.global.console.log([sql, results]);
    }
    me.has_pending_request = false;
    me.cursor_ = results;
    me.current_cursor_index_ = 0;
    if (!!me.index_name && goog.isDefAndNotNull(ini_key)) {
      // skip them
      var cmp = ydn.db.cmp(me.getPrimaryKey(), ini_key);
      while (cmp == -1 || (cmp == 0 && exclusive)) {
        me.current_cursor_index_++;
        cmp = ydn.db.cmp(me.getPrimaryKey(), ini_key);
      }
    }
    me.onSuccess(me.getPrimaryKey(), me.getIndexKey(), me.getValue());
  }
294271
def db_snapshot_append(cls, cur, block_id, consensus_hash, ops_hash, timestamp):
        
        
        query = 'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);'
        args = (block_id,consensus_hash,ops_hash,timestamp)
        
        cls.db_query_execute(cur, query, args)
        return True
529958
function AddrResult(hrp, version, hash) {
  this.hrp = hrp;
  this.version = version;
  this.hash = hash;
}
1129333
def add_block(block, forward_pending_transaction=true)
      unless block.has_parent? || block.genesis?
        logger.debug "missing parent", block_hash: block
        return false
      end

      unless block.validate_uncles
        logger.debug "invalid uncles", block_hash: block
        return false
      end

      unless block.header.check_pow || block.genesis?
        logger.debug "invalid nonce", block_hash: block
        return false
      end

      if block.has_parent?
        begin
          Block.verify(block, block.get_parent)
        rescue InvalidBlock => e
          log.fatal "VERIFICATION FAILED", block_hash: block, error: e

          f = File.join Utils.data_dir, 'badblock.log'
          File.write(f, Utils.encode_hex(RLP.encode(block)))
          return false
        end
      end

      if block.number < head.number
        logger.debug "older than head", block_hash: block, head_hash: head
      end

      @index.add_block block
      store_block block

      # set to head if this makes the longest chain w/ most work for that number
      if block.chain_difficulty > head.chain_difficulty
        logger.debug "new head", block_hash: block, num_tx: block.transaction_count
        update_head block, forward_pending_transaction
      elsif block.number > head.number
        logger.warn "has higher blk number than head but lower chain_difficulty", block_has: block, head_hash: head, block_difficulty: block.chain_difficulty, head_difficulty: head.chain_difficulty
      end

      # Refactor the long calling chain
      block.transactions.clear_all
      block.receipts.clear_all
      block.state.db.commit_refcount_changes block.number
      block.state.db.cleanup block.number

      commit # batch commits all changes that came with the new block
      true
    end
770204
function(transaction, _callback) {
      transaction.remote = api.remote;

      if (options.blockDuplicates === true) {
        blockDuplicates(transaction, options, _callback);
      } else {
        _callback(null, transaction);
      }
    }
226889
public boolean installSnapshot(SnapshotEntry snapshot) {
        long commitIndex = state.commitIndex();
        if (commitIndex > snapshot.index()) {
            logger.info("Ignored stale " + snapshot + ", commit index at: " + commitIndex);
            return false;
        } else if (commitIndex == snapshot.index()) {
            logger.info("Ignored " + snapshot + " since commit index is same.");
            return true;
        }

        state.commitIndex(snapshot.index());
        int truncated = state.log().setSnapshot(snapshot);
        if (truncated > 0) {
            logger.info(truncated + " entries are truncated to install " + snapshot);
        }

        raftIntegration.restoreSnapshot(snapshot.operation(), snapshot.index());

        // If I am installing a snapshot, it means I am still present in the last member list,
        // but it is possible that the last entry I appended before the snapshot could be a membership change.
        // Because of this, I need to update my status.
        // Nevertheless, I may not be present in the restored member list, which is ok.

        setStatus(ACTIVE);
        state.restoreGroupMembers(snapshot.groupMembersLogIndex(), snapshot.groupMembers());
        printMemberState();

        state.lastApplied(snapshot.index());
        invalidateFuturesUntil(snapshot.index(), new StaleAppendRequestException(state.leader()));
        logger.info(snapshot + " is installed.");

        return true;
    }
683145
def _add_blockhash_to_events(storage: SQLiteStorage, cache: BlockHashCache) -> None:
    """"""
    batch_query = storage.batch_query_event_records(
        batch_size=500,
        filters=[('_type', 'raiden.transfer.events.ContractSend%')],
    )
    for events_batch in batch_query:
        updated_events = []
        for event in events_batch:
            data = json.loads(event.data)
            assert 'triggered_by_block_hash' not in data, 'v18 events cant contain blockhash'
            # Get the state_change that triggered the event and get its hash
            matched_state_changes = storage.get_statechanges_by_identifier(
                from_identifier=event.state_change_identifier,
                to_identifier=event.state_change_identifier,
            )
            result_length = len(matched_state_changes)
            msg = 'multiple state changes should not exist for the same identifier'
            assert result_length == 1, msg

            statechange_data = json.loads(matched_state_changes[0])
            if 'block_hash' in statechange_data:
                data['triggered_by_block_hash'] = statechange_data['block_hash']
            elif 'block_number' in statechange_data:
                block_number = int(statechange_data['block_number'])
                data['triggered_by_block_hash'] = cache.get(block_number)

            updated_events.append((
                json.dumps(data),
                event.event_identifier,
            ))

        storage.update_events(updated_events)