See: https://github.com/bitcoin/bips/blob/master/bip-0122.mediawiki
11362
def create_BIP122_uri(
    chain_id: str, resource_type: str, resource_identifier: str
) -> URI:
    
    if resource_type != BLOCK:
        raise ValueError("Invalid resource_type.  Must be one of 'block'")
    elif not is_block_or_transaction_hash(resource_identifier):
        raise ValueError(
            "Invalid resource_identifier.  Must be a hex encoded 32 byte value"
        )
    elif not is_block_or_transaction_hash(chain_id):
        raise ValueError("Invalid chain_id.  Must be a hex encoded 32 byte value")

    return URI(
        parse.urlunsplit(
            [
                "blockchain",
                remove_0x_prefix(chain_id),
                f"{resource_type}/{remove_0x_prefix(resource_identifier)}",
                "",
                "",
            ]
        )
    )
1097880
def extract_pk_blob_from_pyasn1(pyasn1_struct):
    

    pk = pyasn1_struct.getComponentByName(
        "tbsCertificate"
    ).getComponentByName(
        "subjectPublicKeyInfo"
    )

    return pyasn1.codec.der.encoder.encode(pk)
789805
def combine_signatures(*sig_dicts)
      combined = {}
      sig_dicts.each do |sig_dict|
        sig_dict.each do |tree, signature|
          decoded_sig = decode_base58(signature)
          low_s_der_sig = Bitcoin::Script.is_low_der_signature?(decoded_sig) ?
            decoded_sig : Bitcoin::OpenSSL_EC.signature_to_low_s(decoded_sig)
          combined[tree] = Bitcoin::OpenSSL_EC.repack_der_signature(low_s_der_sig)
        end
      end

      # Order of signatures is important for validation, so we always
      # sort public keys and signatures by the name of the tree
      # they belong to.
      combined.sort_by { |tree, value| tree }.map { |tree, sig| sig }
    end
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()
162485
function generateRsJws(protect, bits, key) {
  if (key instanceof Buffer) {
    key = key.toString();
  } else if (typeof key !== 'string') {
    throw new TypeError('Key must be a buffer or a UTF-8 string');
  }
  if (!key.includes('-----BEGIN') || !key.includes('KEY-----')) {
    throw new TypeError('Key must be a PEM formatted RSA private key');
  }
  let signer = crypto.createSign(`SHA${bits}`);
  let signature = buf2b64url(signer.update(protect).sign(key));
  return `${protect}.${signature}`;
}
1089382
function _makeBitReversal() {
    var i = 0,
        j = 0,
        k = 0;
    _bitrev[0] = 0;
    while(++i < _n) {
      k = _n >> 1;
      while(k <= j) {
        j -= k;
        k >>= 1;
      }
      j += k;
      _bitrev[i] = j;
    }
  }
285726
def _make_pkh_address(pubkey_hash, witness=False, cashaddr=True):
    '''
    
    '''
    addr_bytes = bytearray()
    if riemann.network.CASHADDR_P2PKH is not None and cashaddr:
        addr_bytes.extend(riemann.network.CASHADDR_P2PKH)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.CASHADDR_ENCODER.encode(addr_bytes)
    if witness:
        addr_bytes.extend(riemann.network.P2WPKH_PREFIX)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.SEGWIT_ENCODER.encode(addr_bytes)
    else:
        addr_bytes.extend(riemann.network.P2PKH_PREFIX)
        addr_bytes.extend(pubkey_hash)
        return riemann.network.LEGACY_ENCODER.encode(addr_bytes)
862707
def dump_all_keys_or_addrs(wallet_obj):
    '''
    
    '''

    print_traversal_warning()

    puts('\nDo you understand this warning?')
    if not confirm(user_prompt=DEFAULT_PROMPT, default=False):
        puts(colored.red('Dump Cancelled!'))
        return

    mpub = wallet_obj.serialize_b58(private=False)

    if wallet_obj.private_key:
        desc_str = 'private keys'
    else:
        desc_str = 'addresses'
        puts('Displaying Public Addresses Only')
        puts('For Private Keys, please open bcwallet with your Master Private Key:\n')
        priv_to_display = '%s123...' % first4mprv_from_mpub(mpub=mpub)
        print_bcwallet_basic_priv_opening(priv_to_display=priv_to_display)

    puts('How many %s (on each chain) do you want to dump?' % desc_str)
    puts('Enter "b" to go back.\n')

    num_keys = get_int(
            user_prompt=DEFAULT_PROMPT,
            max_int=10**5,
            default_input='5',
            show_default=True,
            quit_ok=True,
            )

    if num_keys is False:
        return

    if wallet_obj.private_key:
        print_childprivkey_warning()

    puts('-' * 70)
    for chain_int in (0, 1):
        for current in range(0, num_keys):
            path = "m/%d/%d" % (chain_int, current)
            if current == 0:
                if chain_int == 0:
                    print_external_chain()
                    print_key_path_header()
                elif chain_int == 1:
                    print_internal_chain()
                    print_key_path_header()
            child_wallet = wallet_obj.get_child_for_path(path)
            if wallet_obj.private_key:
                wif_to_use = child_wallet.export_to_wif()
            else:
                wif_to_use = None
            print_path_info(
                    address=child_wallet.to_address(),
                    path=path,
                    wif=wif_to_use,
                    coin_symbol=coin_symbol_from_mkey(mpub),
                    )

    puts(colored.blue('\nYou can compare this output to bip32.org'))
1021520
def rfc6979_ecdsa_nonce(hash, privkey)
      raise ArgumentError, "Hash must be 32 bytes long" if hash.bytesize != 32
      raise ArgumentError, "Private key must be 32 bytes long" if privkey.bytesize != 32

      autorelease do |pool|
        order = self.group_order

        # Step 3.2.a. hash = H(message). Already performed by the caller.

        # Step 3.2.b. V = 0x01 0x01 0x01 ... 0x01 (32 bytes equal 0x01)
        v = "\x01".b*32

        # Step 3.2.c. K = 0x00 0x00 0x00 ... 0x00 (32 bytes equal 0x00)
        k = "\x00".b*32

        # Step 3.2.d. K = HMAC-SHA256(key: K, data: V || 0x00 || int2octets(privkey) || bits2octets(hash))
        h1 = pool.new_bn(hash)
        BN_div(nil, h1, h1, order, pool.bn_ctx) # h1 = h1 % order
        h1data = data_from_bn(h1, min_length: 32)
        k = BTC.hmac_sha256(key: k, data: v + "\x00".b + privkey + h1data)

        # Step 3.2.e. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.f. K = HMAC-SHA256(key: K, data: V || 0x01 || int2octets(privkey) || bits2octets(hash))
        k = BTC.hmac_sha256(key: k, data: v + "\x01".b + privkey + h1data)

        # Step 3.2.g. V = HMAC-SHA256(key: K, data: V)
        v = BTC.hmac_sha256(key: k, data: v)

        # Step 3.2.h.
        zero32 = "\x00".b*32
        10000.times do
          t = BTC.hmac_sha256(key: k, data: v)
          tn = pool.new_bn(t)
          if BN_cmp(tn, order) < 0
            nonce = data_from_bn(tn, min_length: 32)
            if nonce != zero32
              return nonce
            end
          end
          # Note: the probability of not succeeding at the first try is about 2^-127.
          k = BTC.hmac_sha256(key: k, data: v + zero32)
          v = BTC.hmac_sha256(key: k, data: v)
        end
        # we generated 10000 numbers, none of them is good -> fail.
        raise "Cannot find any good ECDSA nonce after 10000 iterations of RFC6979."
      end
    end
364704
def build_TKIP_payload(data, iv, mac, tk):
    
    TSC5, TSC4, TSC3, TSC2, TSC1, TSC0 = (
        (iv >> 40) & 0xFF,
        (iv >> 32) & 0xFF,
        (iv >> 24) & 0xFF,
        (iv >> 16) & 0xFF,
        (iv >> 8) & 0xFF,
        iv & 0xFF
    )
    bitfield = 1 << 5  # Extended IV
    TKIP_hdr = chb(TSC1) + chb((TSC1 | 0x20) & 0x7f) + chb(TSC0) + chb(bitfield)  # noqa: E501
    TKIP_hdr += chb(TSC2) + chb(TSC3) + chb(TSC4) + chb(TSC5)

    TA = [orb(e) for e in mac2str(mac)]
    TSC = [TSC0, TSC1, TSC2, TSC3, TSC4, TSC5]
    TK = [orb(x) for x in tk]

    rc4_key = gen_TKIP_RC4_key(TSC, TA, TK)
    return TKIP_hdr + ARC4_encrypt(rc4_key, data)
169414
def get_nonce(block_representation, coin_symbol='btc', api_key=None):
    '''
    
    '''
    return get_block_overview(block_representation=block_representation,
            coin_symbol=coin_symbol, txn_limit=1, api_key=api_key)['bits']
444010
function b64toBlob(b64Data, contentType, sliceSize) {
	contentType = contentType || '';
	sliceSize = sliceSize || 512;

	var byteCharacters = atob(b64Data);
	var byteArrays = [];

	for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
		var slice = byteCharacters.slice(offset, offset + sliceSize);

		var byteNumbers = new Array(slice.length);
		for (var i = 0; i < slice.length; i++) {
			byteNumbers[i] = slice.charCodeAt(i);
		}

		var byteArray = new Uint8Array(byteNumbers);

		byteArrays.push(byteArray);
	}

	var blob = new Blob(byteArrays, {type: contentType});
	return blob;
}
32650
function decryptRaw (buffer, passphrase, progressCallback, scryptParams) {
  // 39 bytes: 2 bytes prefix, 37 bytes payload
  if (buffer.length !== 39) throw new Error('Invalid BIP38 data length')
  if (buffer.readUInt8(0) !== 0x01) throw new Error('Invalid BIP38 prefix')
  scryptParams = scryptParams || SCRYPT_PARAMS

  // check if BIP38 EC multiply
  var type = buffer.readUInt8(1)
  if (type === 0x43) return decryptECMult(buffer, passphrase, progressCallback, scryptParams)
  if (type !== 0x42) throw new Error('Invalid BIP38 type')

  passphrase = Buffer.from(passphrase, 'utf8')

  var flagByte = buffer.readUInt8(2)
  var compressed = flagByte === 0xe0
  if (!compressed && flagByte !== 0xc0) throw new Error('Invalid BIP38 compression flag')

  var N = scryptParams.N
  var r = scryptParams.r
  var p = scryptParams.p

  var salt = buffer.slice(3, 7)
  var scryptBuf = scrypt(passphrase, salt, N, r, p, 64, progressCallback)
  var derivedHalf1 = scryptBuf.slice(0, 32)
  var derivedHalf2 = scryptBuf.slice(32, 64)

  var privKeyBuf = buffer.slice(7, 7 + 32)
  var decipher = aes.createDecipheriv('aes-256-ecb', derivedHalf2, NULL)
  decipher.setAutoPadding(false)
  decipher.end(privKeyBuf)

  var plainText = decipher.read()
  var privateKey = xor(derivedHalf1, plainText)

  // verify salt matches address
  var d = BigInteger.fromBuffer(privateKey)
  var address = getAddress(d, compressed)
  var checksum = hash256(address).slice(0, 4)
  assert.deepEqual(salt, checksum)

  return {
    privateKey: privateKey,
    compressed: compressed
  }
}
1015389
function generateBKP (pkp) {
  const buffer = new Buffer(pkp, 'base64')
  const hash = crypto.createHash('sha1')
  hash.update(buffer)
  const sha1str = hash.digest('hex').toUpperCase()
  return sha1str.match(/(.{1,8})/g).join('-')
}
340916
def binary2pb(b, proto_id, proto_fmt_type):
    
    rsp = pb_map[proto_id]
    if rsp is None:
        return None
    if proto_fmt_type == ProtoFMT.Json:
        return json2pb(type(rsp), b.decode('utf-8'))
    elif proto_fmt_type == ProtoFMT.Protobuf:
        rsp = type(rsp)()
        # logger.debug((proto_id))
        if IS_PY2:
            rsp.ParseFromString(str(b))
        else:
            rsp.ParseFromString(b)
        return rsp
    else:
        raise Exception("binary2str: unknown proto format.")
300539
def to_base58
      h = to_payload.bth
      hex = h + Bitcoin.calc_checksum(h)
      Base58.encode(hex)
    end
1243201
def i2b(self, pkt, x):
        """"""
        if type(x) is str:
          x = bytes([ ord(i) for i in x ])
        return x