Got a block.
        * validate it
        * load its transactions
        * ask for each transaction's sender transaction
338533
def handle_block( self, message_header, block ):
        

        if self.have_all_block_data():
            self.loop_exit()
            return

        block_hash = block.calculate_hash()
        
        # is this a solicited block?
        if block_hash not in self.block_info.keys():
            log.error("Ignoring unsolicited block %s" % block_hash)
            return
        
        header = self.block_info[block_hash]['header']
        height = self.block_info[block_hash]['height']
        
        log.debug("handle block %s (%s)" % (height, block_hash))

        # does this block's transaction hashes match the merkle root?
        tx_hashes = [block.txns[i].calculate_hash() for i in range(0, len(block.txns))]
        block_merkle_tree = merkle.MerkleTree(tx_hashes)
        mr = block_merkle_tree.root()

        if mr != header['merkle_root']:
            log.error("Merkle root of %s (%s) mismatch: expected %s, got %s" % (block_hash, height, header['merkle_root'], mr))
            return

        merkle_paths = {}       # map txid to merkle path

        # make sure we have merkle paths for each tx
        for i in range(0, len(block.txns)):
            txid = block.txns[i].calculate_hash()
            merkle_path = block_merkle_tree.path(txid)
            if merkle_path is None:
                log.error("No merkle path for {}".format(txid))
                return 

            merkle_paths[txid] = merkle_path
 
        nulldata_txs = []
        relindex = 0
        for txindex in range(0, len(block.txns)):

            txdata = self.parse_tx( block.txns[txindex], header, block_hash, txindex )

            # if there is no nulldata output, then we don't care about this one.
            has_nulldata = False
            nulldata_payload = None

            for outp in txdata['outs']:
                script_type = bits.btc_script_classify(outp['script'])
                if script_type == 'nulldata':
                    # to be clear, we only care about outputs that take the form
                    # OP_RETURN <string length> <string data>
                    nulldata_script = bits.btc_script_deserialize(outp['script'])
                    if len(nulldata_script) < 2:
                        # malformed OP_RETURN; no data after '6a'
                        nulldata_payload = None
                        has_nulldata = False

                    elif len(nulldata_script) == 2 and isinstance(nulldata_script[1], (str,unicode)):
                        # well-formed OP_RETURN output
                        nulldata_payload = nulldata_script[1]
                        has_nulldata = True
                   
                    else:
                        # this is something like OP_RETURN OP_2 (e.g. "6a52")
                        # there's nothing for us here.
                        nulldata_payload = None
                        has_nulldata = False

            # count all txs processed
            self.num_txs_processed += 1

            if not has_nulldata:
                continue

            # remember nulldata, even if it's empty
            txdata['nulldata'] = nulldata_payload 

            # remember merkle path
            txdata['tx_merkle_path'] = merkle_paths[txdata['txid']]
            
            # calculate total output (part of fee; will be debited when we discover the senders)
            # NOTE: this works because we have out['value'] as type Decimal
            # txdata['fee'] -= sum( int(out['value'] * 10**8) for out in txdata['vout'] )
            txdata['fee'] -= sum(out['value'] for out in txdata['outs'])

            # remember the relative tx index (i.e. the ith nulldata tx)
            txdata['relindex'] = relindex
            
	    # do we actually want this?
            if self.tx_filter is not None:
                if not self.tx_filter( txdata ):
                    continue

            # yup, we want it!
            relindex += 1
            nulldata_txs.append( txdata )


        self.block_info[block_hash]['txns'] = nulldata_txs
        self.block_info[block_hash]['num_txns'] = len(block.txns)
        self.block_info[block_hash]['num_senders'] = 0

        # get each input's transaction
        sender_txhashes = []

        for txn in self.block_info[block_hash]['txns']:
            for i in range(0, len(txn['ins'])):

                # record information about the transaction
                # that created this input (so we can go find
                # it later).
                inp = txn['ins'][i]
                sender_txid = inp['outpoint']['hash']
                inp_sender_outp = inp['outpoint']['index']

                if str(sender_txid) not in sender_txhashes:
                    sender_txhashes.append( str(sender_txid) )

                sinfo = self.make_sender_info( block_hash, txn, i, height )

                if not self.sender_info.has_key(sender_txid):
                    # map outpoint for this input to the tx info
                    self.sender_info[sender_txid] = {}

                # sinfo is the information from the output in 
                # the sender-tx that funded inp
                self.sender_info[sender_txid][inp_sender_outp] = sinfo

        # update accounting...
        self.num_blocks_received += 1
        self.block_info[block_hash]['handled'] = True

        log.debug("Request %s nulldata sender TXs" % len(sender_txhashes))

        if self.have_all_block_data():
            self.loop_exit()

        return
109070
def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain:
    
    if not isinstance(chain, MiningChain):
        raise ValidationError('`mine_block` may only be used on MiningChain instances')
    chain.mine_block(**kwargs)
    return chain
1117467
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    response = await client(bma.node.summary)
    print(response)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    response = await client(bma.blockchain.parameters)
    print(response)

    # Get the current block
    print("\nCall bma.blockchain.current:")
    response = await client(bma.blockchain.current)
    print(response)

    # Get the block number 10
    print("\nCall bma.blockchain.block(10):")
    response = await client(bma.blockchain.block, 10)
    print(response)

    # jsonschema validator
    summary_schema = {
        "type": "object",
        "properties": {
            "duniter": {
                "type": "object",
                "properties": {
                    "software": {
                        "type": "string"
                    },
                    "version": {
                        "type": "string",
                    },
                    "forkWindowSize": {
                        "type": "number"
                    }
                },
                "required": ["software", "version"]
            },
        },
        "required": ["duniter"]
    }

    # Get the node summary infos (direct REST GET request)
    print("\nCall direct get on node/summary")
    response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema)
    print(response)

    # Close client aiohttp session
    await client.close()
862914
def handle_block(
        target_state: TargetTransferState,
        channel_state: NettingChannelState,
        block_number: BlockNumber,
        block_hash: BlockHash,
) -> TransitionResult[TargetTransferState]:
    
    transfer = target_state.transfer
    events: List[Event] = list()
    lock = transfer.lock

    secret_known = channel.is_secret_known(
        channel_state.partner_state,
        lock.secrethash,
    )
    lock_has_expired, _ = channel.is_lock_expired(
        end_state=channel_state.our_state,
        lock=lock,
        block_number=block_number,
        lock_expiration_threshold=channel.get_receiver_expiration_threshold(lock),
    )

    if lock_has_expired and target_state.state != 'expired':
        failed = EventUnlockClaimFailed(
            identifier=transfer.payment_identifier,
            secrethash=transfer.lock.secrethash,
            reason=f'lock expired',
        )
        target_state.state = TargetTransferState.EXPIRED
        events = [failed]
    elif secret_known:
        events = events_for_onchain_secretreveal(
            target_state=target_state,
            channel_state=channel_state,
            block_number=block_number,
            block_hash=block_hash,
        )

    return TransitionResult(target_state, events)
1220094
async function startSecondChain() {

	// First we'll add some logic to actually request the data
	// Normally you would add some network logic here,
	// but for this example we'll just go steal the blocks from block_one
	//
	// The `getBlocks` function receives 3 parameters:
	//  - requested_blocks      : An array of indexes of blocks to get (can also be empty)
	//  - last_available_block  : The last available block in our chain, so newer once are also welcome
	//  - callback              : A callback where we can send the array response to
	chain_two.setBlockRequester(function getBlocks(requested_blocks, last_available_block, callback) {

		var new_block_buffers = [],
		    i;

		// No blocks? Get them all then
		if (!last_available_block) {
			i = 0;
		} else {
			i = last_available_block.index;
		}

		console.log('Requesting new blocks starting with index:', i, '...');

		// Get the binary buffers from chain_one
		// As I said: you would probably add network logic here.
		// So: send a request to another network for the wanted blocks,
		// and then receive them over a Socket as binary data
		for (; i < chain_one.length; i++) {
			new_block_buffers.push(chain_one.getByIndex(i).buffer);
		}

		console.log('   » Found', new_block_buffers.length, 'new blocks for the second chain\n');

		callback(null, new_block_buffers);
	});

	// Do a manual request for blocks
	await chain_two.requestUpdate();

	console.log('Chain two has requested and received all missing blocks');

	await chain_two.isValid();

	console.log('Chain two is valid!');

	// Now we'll test fork behaviour

	// Mine 2 new blocks on chain one and add them
	chain_one.addTransaction({test: 1}, private_key_one);
	let block_one = await chain_one.minePendingTransactions(private_key_one, public_key_one);
	chain_one.addBlock(block_one);

	chain_one.addTransaction({test: 1}, private_key_one);
	block_one = await chain_one.minePendingTransactions(private_key_one, public_key_one);
	chain_one.addBlock(block_one);

	// Mine 1 new block on chain 2
	chain_two.addTransaction({test: 1}, private_key_two);
	let block_two = await chain_two.minePendingTransactions(private_key_two, public_key_two);
	chain_two.addBlock(block_two);

	// Let chain_two, which has a "wrong" block in its chain, request new blocks
	await chain_two.requestUpdate();

	console.log('Second chain has been updated and contains a fork, resolving...');

	let switched_fork = await chain_two.resolveConflicts();

	console.log('Switched to fork:', switched_fork);
}
863852
def block_data_sanity_checks(self):
        
        assert self.have_all_block_data(), "Still missing block data"
        assert self.num_txs_received == len(self.sender_info.keys()), "Num TXs received: %s; num TXs requested: %s" % (self.num_txs_received, len(self.sender_info.keys()))

        for (block_hash, block_info) in self.block_info.items():
            for tx in block_info['txns']:
                assert None not in tx['senders'], "Missing one or more senders in %s; dump follows\n%s" % (tx['txid'], simplejson.dumps(tx, indent=4, sort_keys=True)) 
                for i in range(0, len(tx['ins'])):
                    inp = tx['ins'][i]
                    sinfo = tx['senders'][i]

                    assert sinfo['txid'] in self.sender_info, 'Surreptitious sender tx {}'.format(sinfo['txid'])
                    assert inp['outpoint']['index'] == sinfo['nulldata_vin_outpoint'], 'Mismatched sender/input index ({}: {} != {}); dump follows\n{}'.format(
                            sinfo['txid'], inp['outpoint']['index'], sinfo['nulldata_vin_outpoint'], simplejson.dumps(tx, indent=4, sort_keys=True))

                    assert inp['outpoint']['hash'] == sinfo['txid'], 'Mismatched sender/input txid ({} != {}); dump follows\n{}'.format(inp['txid'], sinfo['txid'], simplejson.dumps(tx, indent=4, sort_keys=True))

        return True
905748
private void checkTransactions(final int height, final EnumSet<VerifyFlag> flags)
            throws VerificationException {
        // The first transaction in a block must always be a coinbase transaction.
        if (!transactions.get(0).isCoinBase())
            throw new VerificationException("First tx is not coinbase");
        if (flags.contains(Block.VerifyFlag.HEIGHT_IN_COINBASE) && height >= BLOCK_HEIGHT_GENESIS) {
            transactions.get(0).checkCoinBaseHeight(height);
        }
        // The rest must not be.
        for (int i = 1; i < transactions.size(); i++) {
            if (transactions.get(i).isCoinBase())
                throw new VerificationException("TX " + i + " is coinbase when it should not be.");
        }
    }
234265
def get_block_statuses(self, block_ids):
        
        try:
            return [
                (block_id.hex(),
                 self._chain_controller.block_validation_result(
                     block_id.hex()))
                for block_id in block_ids
            ]
        except KeyError as key_error:
            raise UnknownBlock(key_error.args[0])
761209
def each_registered_block(type, &block)
        klass = self.class
        while klass.respond_to?(type)
          klass.public_send(type).each(&block)
          klass = klass.superclass
        end
      end
199461
def _load_blocks(self, blocks: List[Tuple[Key, Any]]) -> List[TimeAggregate]:
        
        return [
            TypeLoader.load_item(self._schema.source.type)(self._schema.source, self._identity,
                                                           EvaluationContext()).run_restore(block)
            for (_, block) in blocks
        ]
424312
def app(&block)
      raise ArgumentError, "Block is required" unless block_given?
      lambda do |env|
        Rango::Router.set_rack_env(env)
        request = Rango::Request.new(env)
        response = Rack::Response.new
        body = block.call(request, response)
        # TODO: check how rack test if object is stringable, probably not this way
        raise ArgumentError, "It has to return a valid rack body, #{body.inspect} returned" unless body.respond_to?(:each) || body.is_a?(String)
        response.write(body)
        array = response.finish
        [array[0], array[1], body] # we don't want to have Rack::Response instance instead body, it's mess!
      end
    end
106891
def _get_block_transactions(
            self,
            transaction_root: Hash32,
            transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']:
        
        for encoded_transaction in self._get_block_transaction_data(self.db, transaction_root):
            yield rlp.decode(encoded_transaction, sedes=transaction_class)
803596
def getBlock(self, block_identifier, full_transactions=False):
        
        method = select_method_for_block_identifier(
            block_identifier,
            if_predefined='eth_getBlockByNumber',
            if_hash='eth_getBlockByHash',
            if_number='eth_getBlockByNumber',
        )

        result = self.web3.manager.request_blocking(
            method,
            [block_identifier, full_transactions],
        )
        if result is None:
            raise BlockNotFound(f"Block with id: {block_identifier} not found.")
        return result
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
1125628
def fetch_block(block_size=nil)
      block_size ||= @block_size ||= @options.fetch(:block_size) { 1000 }
      @result = @connection.execute("fetch #{block_size} from cursor_#{@cursor}")

      if @iterate == :each_array
        @block = @result.each_row.collect {|row| row }
      else
        @block = @result.collect {|row| row }
      end
    end
1037764
async function sendTransaction (tx, options = {}) {
  const { waitMined, verify } = R.merge(this.Chain.defaults, options)
  // Verify transaction before broadcast
  if (this.verifyTxBeforeSend || verify) {
    const { validation, tx: txObject, txType } = await this.unpackAndVerify(tx)
    if (validation.length) {
      throw Object.assign(Error('Transaction verification error'), {
        code: 'TX_VERIFICATION_ERROR',
        errorData: { validation, tx: txObject, txType },
        txHash: tx
      })
    }
  }

  try {
    const { txHash } = await this.api.postTransaction({ tx })
    return waitMined ? { ...(await this.poll(txHash, options)), rawTx: tx } : { hash: txHash, rawTx: tx }
  } catch (e) {
    throw Object.assign(
      (new Error(e.message)),
      {
        rawTx: tx,
        verifyTx: () => this.unpackAndVerify(tx)
      }
    )
  }
}
1365414
def mine_block(self, *args: Any, **kwargs: Any) -> BaseBlock:
        
        packed_block = self.pack_block(self.block, *args, **kwargs)

        final_block = self.finalize_block(packed_block)

        # Perform validation
        self.validate_block(final_block)

        return final_block