Пример #1
0
    def test_demo_user_keys(self):
        sk_base58 = b"29oiwbqkhLGBuX5teL5d2vsiJ3EXk3dpyBiPwA7W9DJG"
        sk_decoded = base58.b58decode(sk_base58)
        hash = pyscrypt.hash(password=b"demouser",
                             salt=b"demouser",
                             N=1024,
                             r=1,
                             p=1,
                             dkLen=32)

        sk = base58.b58encode(hash)
        hex_sk = binascii.b2a_hex(hash)
        print('Secret Key:', sk, 'length: ', len(sk))
        self.assertEqual(sk_base58, sk)
        self.assertEqual(sk_decoded, hash)

        #print(sk)
        keypair = libnacl.public.SecretKey(hash)

        # 2ipFYsqXnrw4Mt2RUWzEQntAH1FEFB8R52rAT3eExn9S
        pk_base58 = base58.b58encode(keypair.pk)
        pk_decoded = base58.b58decode(pk_base58)

        self.assertEqual(pk_decoded, keypair.pk)
        print('Public Key:', pk_base58, 'length: ', len(pk_base58))

        print("XID: ", crypto.key_to_xid(keypair.pk))
def print_info(key, chain):
  
  prv_key = key.to_extended_key(include_prv=key.prvkey())
  pub_key = key.to_extended_key()

  desc ='  * [Chain m'
  for c in chain:
    if c&0x80000000:
      desc = desc + '/%d\'' % (c & ~0x80000000)
    else:
      desc = desc + '/%d' % c
  desc = desc + ']'

  print desc

  print '    * Identifier'
  print '      * (hex):       %s' % base58.hash_160(point_compress(key.point())).encode('hex')
  print '      * (fpr):       0x%s' % key.fingerprint().encode('hex')
  print '      * (main addr): %s' % key.address()
  print '    * Secret key'
  print '      * (hex):       %s' % key.prvkey().encode('hex')
  print '      * (wif):       %s' % SecretToASecret(key.prvkey(), True)
  print '    * Public key'
  print '      * (hex):       %s' % point_compress(key.point()).encode('hex')
  print '    * Chain code'
  print '      * (hex):       %s' % key.chain().encode('hex')
  print '    * Serialized'
  print '      * (pub hex):   %s' % base58.b58decode(pub_key, None).encode('hex')
  print '      * (prv hex):   %s' % base58.b58decode(prv_key, None).encode('hex')
  print '      * (pub b58):   %s' % pub_key
  print '      * (prv b58):   %s' % prv_key
Пример #3
0
def test_compare_identities():
    cryptonym = 'BPtrqHo3WyjmTNpVchEhWxp3qfDdssdFUNoM8kmKoEWw'
    did_id = 'L5AD5g65TDQr1PPHHRoiGf'
    did_verkey = 'Bf9Z1tKWpcJAvKJVhZhvVZ'

    did_to_cryptonym = base58.b58encode(
        base58.b58decode(did_id) + base58.b58decode(did_verkey)).decode("utf-8")
    assert cryptonym == did_to_cryptonym
Пример #4
0
 def compare_hmac(self, message, token):
     decoded_token = base58.b58decode(token)
     target = base58.b58decode(self.get_hmac(message))
     try:
         assert len(decoded_token) == len(target), "Length mismatch"
         r = hmac.compare_digest(decoded_token, target)
     except:
         return False
     return r
Пример #5
0
 def __init__(self, verkey, identifier=None):
     self._verkey = None
     self._vr = None
     if identifier:
         rawIdr = b58decode(identifier)
         if len(rawIdr) == 32 and not verkey:  # assume cryptonym
             verkey = identifier
         if verkey[0] == '~':  # abbreviated
             verkey = b58encode(b58decode(identifier) +
                                b58decode(verkey[1:]))
     self.verkey = verkey
Пример #6
0
def privkey_b58_bin(priv_b58):
	"""Convert a base-58 private key (ignoring whitespace) into a binary
	string."""
	# Cut out whitespace
	priv_b58 = re.sub("[ \t\n]", "", priv_b58)
	if len(priv_b58) == 381:
		return base58.b58decode(priv_b58, 279)
	elif len(priv_b58) == 44:
		return base58.b58decode(priv_b58, 32)
	else:
		raise ValueError("Expected a key of 44 or 381 base-58 digits")
Пример #7
0
    def parse_dict(self, data):
        """
        Generate fulfillment payload from a dict

        Args:
            data (dict): description of the fulfillment

        Returns:
            Fulfillment
        """
        self.public_key = base58.b58decode(data['public_key'])
        if data['signature']:
            self.signature = base58.b58decode(data['signature'])
Пример #8
0
    def doAttrDisclose(self, origin, target, txnId, key):
        box = libnacl.public.Box(b58decode(origin), b58decode(target))

        data = json.dumps({TXN_ID: txnId, SKEY: key})
        nonce, boxedMsg = box.encrypt(data.encode(), pack_nonce=False)

        op = {
            TARGET_NYM: target,
            TXN_TYPE: DISCLO,
            NONCE: b58encode(nonce).decode("utf-8"),
            DATA: b58encode(boxedMsg).decode("utf-8")
        }
        self.submit(op, identifier=origin)
Пример #9
0
 def test_deteministic_key_pair_is_same(self):
     seed = b'm\xea#\xbb\xady\xea\xf5Y\x1fz\xe5\xd0\x9d\x0f&\xee\xfb=$u\x08\x80\x04\xcf\xf1\x14*\xc9\x0e<g'
     sk_b58, vk_b58 = ed25519_generate_key_pair(seed)
     sk_2_b58, vk_2_b58 = ed25519_generate_key_pair(seed)
     assert len(base58.b58decode(sk_b58)) == 32
     assert len(base58.b58decode(vk_b58)) == 32
     assert SigningKey(sk_b58).encode() == sk_b58
     assert VerifyingKey(vk_b58).encode() == vk_b58
     assert len(base58.b58decode(sk_2_b58)) == 32
     assert len(base58.b58decode(vk_2_b58)) == 32
     assert SigningKey(sk_2_b58).encode() == sk_2_b58
     assert VerifyingKey(vk_2_b58).encode() == vk_2_b58
     assert sk_b58 == sk_2_b58
     assert vk_b58 == vk_2_b58
Пример #10
0
    def _sign_simple_signature_fulfillment(cls, input_, message, key_pairs):
        """Signs a Ed25519Fulfillment.

            Args:
                input_ (:class:`~bigchaindb.common.transaction.
                    Input`) The input to be signed.
                message (str): The message to be signed
                key_pairs (dict): The keys to sign the Transaction with.
        """
        # NOTE: To eliminate the dangers of accidentally signing a condition by
        #       reference, we remove the reference of input_ here
        #       intentionally. If the user of this class knows how to use it,
        #       this should never happen, but then again, never say never.
        input_ = deepcopy(input_)
        public_key = input_.owners_before[0]
        try:
            # cryptoconditions makes no assumptions of the encoding of the
            # message to sign or verify. It only accepts bytestrings
            input_.fulfillment.sign(
                message.encode(),
                base58.b58decode(key_pairs[public_key].encode()),
            )
        except KeyError:
            raise KeypairMismatchException('Public key {} is not a pair to '
                                           'any of the private keys'
                                           .format(public_key))
        return input_
Пример #11
0
    def decode(data: str) -> bytes:
        """
        Decode Base58 string data and return bytes

        :param data: Base58 string
        """
        return base58.b58decode(data)
Пример #12
0
 def decode_zappa_cookie(self, encoded_zappa):
     """
     Eat our Zappa cookie.
     Save the parsed cookies, as we need to send them back on every update.
     """
     self.decoded_zappa = base58.b58decode(encoded_zappa)
     self.request_cookies = json.loads(self.decoded_zappa)
Пример #13
0
 def bip38_decrypt(self,encrypted_privkey,passphrase):
     '''BIP0038 non-ec-multiply decryption. Returns hex privkey.'''
     d = base58.b58decode(encrypted_privkey)
     d = d[2:]
     flagbyte = d[0:1]
     d = d[1:]
     # respect flagbyte, return correct pair
     if flagbyte == '\xc0':
         self.compressed = False
     if flagbyte == '\xe0':
         self.compressed = True
     addresshash = d[0:4]
     d = d[4:-4]
     key = scrypt.hash(passphrase,addresshash, 16384, 8, 8)
     derivedhalf1 = key[0:32]
     derivedhalf2 = key[32:64]
     encryptedhalf1 = d[0:16]
     encryptedhalf2 = d[16:32]
     aes = AES.new(derivedhalf2)
     decryptedhalf2 = aes.decrypt(encryptedhalf2)
     decryptedhalf1 = aes.decrypt(encryptedhalf1)
     priv = decryptedhalf1 + decryptedhalf2
     priv = binascii.unhexlify('%064x' % (long(binascii.hexlify(priv), 16) ^ long(binascii.hexlify(derivedhalf1), 16)))
     pub = privtopub(priv)
     if self.compressed:
         pub = encode_pubkey(pub,'hex_compressed')
     addr = pubtoaddr(pub)
     if hashlib.sha256(hashlib.sha256(addr).digest()).digest()[0:4] != addresshash:
         wx.MessageBox(messages.addresshash,
                       'Addresshash Error')
         # TODO: investigate
         #self.decrypt_priv(wx.PostEvent) # start over
     else:
         return priv
Пример #14
0
 def decode(key):
     """
     Decode the base58 private_value to decimale
     """
     private_value_hex = binascii.hexlify(base58.b58decode(key))
     private_value = bitcoin.decode_privkey(private_value_hex)
     return private_value
Пример #15
0
 def decode(public_value_compressed_base58):
     """
     Decode the base58 public_value to the decimal x and y values
     """
     public_value_compressed_hex = binascii.hexlify(base58.b58decode(public_value_compressed_base58))
     public_value_x, public_value_y = bitcoin.decode_pubkey(public_value_compressed_hex.decode())
     return (public_value_x, public_value_y)
Пример #16
0
def test_round_trips():
    possible_bytes = [b'\x00', b'\x01', b'\x10', b'\xff']
    for length in range(0, 5):
        for bytes_to_test in product(possible_bytes, repeat=length):
            bytes_in = b''.join(bytes_to_test)
            bytes_out = b58decode(b58encode(bytes_in))
            assert_that(bytes_in, equal_to(bytes_out))
Пример #17
0
def _fulfillment_from_details(data, _depth=0):
    """
    Load a fulfillment for a signing spec dictionary

    Args:
        data: tx.output[].condition.details dictionary
    """
    if _depth == 100:
        raise ThresholdTooDeep()

    if data['type'] == 'ed25519-sha-256':
        public_key = base58.b58decode(data['public_key'])
        return Ed25519Sha256(public_key=public_key)

    if data['type'] == 'rsa-sha-256':
        m_int = base58.b58decode_int(data['public_key'])
        m_bytes = m_int.to_bytes(
            (m_int.bit_length() + 7) // 8, 'big'
        )

        rsa_sha256 = RsaSha256()
        rsa_sha256._set_public_modulus(m_bytes)
        return rsa_sha256

    if data['type'] == 'threshold-sha-256':
        threshold = ThresholdSha256(data['threshold'])
        for cond in data['subconditions']:
            cond = _fulfillment_from_details(cond, _depth+1)
            threshold.add_subfulfillment(cond)
        return threshold

    raise UnsupportedTypeError(data.get('type'))
Пример #18
0
def priv_key_decode(keyb58):
    raw = hexlify(b58decode(keyb58))
    h_key = raw[:66]
    cksum = sha256(sha256(unhexlify(h_key)).digest()).hexdigest()[:8]
    if cksum != raw[66:].decode('utf-8'):
        raise ValueError('checksum mismatch')
    return h_key[2:].decode('utf-8')
Пример #19
0
def validate_xid(addr):
    """
    Check if the provided address is valid or not.

    :param addr: address in base58 string.
    :return:
    """
    val = base58.b58decode(addr)
    #assert len(val) == 35

    if len(val) != 35:
        return False

    prefix = val[0]
    if prefix != XID_PREFIX:
        return False

    sha256 = hashlib.sha256()
    sha256.update(XID_PREFIX)
    sha256.update(val[1:33])
    s = sha256.digest()

    if val[-2:] != s[:2]:
        return False

    return True
Пример #20
0
def xid_to_key(xid):
    """
    Retrieve the key from an XID.

    :param xid:
    :return:
    """
    val = base58.b58decode(xid)

    if len(val) != 35:
        return None

    prefix = val[0]
    if prefix != XID_PREFIX:
        return None

    key = val[1:33]
    sha256 = hashlib.sha256()
    sha256.update(XID_PREFIX)
    sha256.update(key)
    s = sha256.digest()

    if val[-2:] != s[:2]:
        return None

    return key
Пример #21
0
def validate_key_string(pk_str):
    """
    Validates a given public key string.
    :param sk_str:
    :return:
    """
    val = base58.b58decode(pk_str)
    #assert len(val) == 35

    if len(val) != 35:
        return False

    prefix = val[0]
    if prefix != KEY_PREFIX:
        return False

    sha256 = hashlib.sha256()
    sha256.update(KEY_PREFIX)
    sha256.update(val[1:33])
    s = sha256.digest()

    if val[-2:] != s[:2]:
        return False

    return True
Пример #22
0
def detect(addr):
    """Detect the currency type of an address.

    :addr: string, cryptocurrency address
    :returns: list of dicts with name of currency and type public or private.

    """
    # check for valid address
    if not validate(addr):
        raise Exception('Invalid address.')

    version = ord(base58.b58decode(addr)[0])
    det = []
    for c, p in versions.items():
        res = {'currency': None, 'type': None}
        if p['pub'] == version:
            res['currency'] = c
            res['type'] = 'pub'
            det.append(res)
        elif p['priv'] == version:
            res['currency'] = c
            res['type'] = 'priv'
            det.append(res)

    return det
Пример #23
0
    def verifySignature(self, msg: Dict[str, str]):
        signature = msg.get(f.SIG.nm)
        identifier = msg.get(IDENTIFIER)
        msgWithoutSig = {k: v for k, v in msg.items() if k != f.SIG.nm}
        # TODO This assumes the current key is the cryptonym. This is a BAD
        # ASSUMPTION!!! Indy needs to provide the current key.
        ser = serialize_msg_for_signing(msgWithoutSig)
        signature = b58decode(signature.encode())
        typ = msg.get(TYPE)
        # TODO: Maybe keeping ACCEPT_INVITE open is a better option than keeping
        # an if condition here?
        if typ == ACCEPT_INVITE:
            verkey = msg.get(VERKEY)
        else:
            try:
                link = self.getLinkForMsg(msg)
                verkey = self.getVerkeyForLink(link)
            except (ConnectionNotFound, VerkeyNotFound):
                # This is for verification of `NOTIFY` events
                link = self.wallet.getConnectionBy(remote=identifier)
                # TODO: If verkey is None, it should be fetched from Indy.
                # Assuming CID for now.
                verkey = link.remoteVerkey

        v = DidVerifier(verkey, identifier=identifier)
        if not v.verify(signature, ser):
            raise SignatureRejected
        else:
            if typ == ACCEPT_INVITE:
                self.logger.info('Signature accepted.')
            return True
Пример #24
0
    def authenticate_multi(self, msg: Dict, signatures: Dict[str, str],
                           threshold: Optional[int]=None, verifier: Verifier=DidVerifier):
        num_sigs = len(signatures)
        if threshold is not None:
            if num_sigs < threshold:
                raise InsufficientSignatures(num_sigs, threshold)
        else:
            threshold = num_sigs
        correct_sigs_from = []
        for idr, sig in signatures.items():
            try:
                sig = base58.b58decode(sig)
            except Exception as ex:
                raise InvalidSignatureFormat from ex

            ser = self.serializeForSig(msg, identifier=idr)
            verkey = self.getVerkey(idr)

            if verkey is None:
                raise CouldNotAuthenticate(
                    'Can not find verkey for {}'.format(idr))

            vr = verifier(verkey, identifier=idr)
            if vr.verify(sig, ser):
                correct_sigs_from.append(idr)
                if len(correct_sigs_from) == threshold:
                    break
        else:
            raise InsufficientCorrectSignatures(len(correct_sigs_from),
                                                threshold)
        return correct_sigs_from
Пример #25
0
	def from_extended_key(klass, extended_key):
		decoded = base58.b58decode(extended_key, 78+4)
		assert(decoded)
		ekdata = decoded[:78]
		checksum = decoded[78:78+4]
		# validate checksum
		valid_checksum = hashlib.sha256(hashlib.sha256(ekdata).digest()).digest()[:4]
		assert (checksum == valid_checksum)

		
		version = util.string_to_number(ekdata[0:0+4])
		depth   = util.string_to_number(ekdata[4:4+1])
		parentfp = ekdata[5:5+4]
		childnum = util.string_to_number(ekdata[9:9+4])
		chaincode = ekdata[13:13+32]
		data = ekdata[45:45+33]

		testnet = version in (0x043587CF, 0x04358394)
		
		if version in (0x0488B21E, 0x043587CF): # data contains pubkey
			assert data[0] in ('\x02', '\x03')
			key = point_decompress(SECP256k1.curve, data)
		elif version in (0x0488ADE4, 0x04358394): # data contains privkey
			assert data[0] == '\x00'
			key = util.string_to_number(data[1:])
		else:
			raise Exception('unknown version')

		return klass(key, chaincode, 
			testnet=testnet,
			depth=depth,
			childnum=childnum,
			parentfp=parentfp)
Пример #26
0
def bip38_decrypt(encrypted_privkey,passphrase):
    '''BIP0038 non-ec-multiply decryption. Returns WIF privkey.'''
    d = base58.b58decode(encrypted_privkey)
    d = d[2:]
    flagbyte = d[0:1]
    d = d[1:]
    if flagbyte == '\xc0':
        compressed = False
    if flagbyte == '\xe0':
        compressed = True
    addresshash = d[0:4]
    d = d[4:-4]
    key = scrypt.hash(passphrase,addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    priv = decryptedhalf1 + decryptedhalf2
    priv = binascii.unhexlify('%064x' % (long(binascii.hexlify(priv), 16) ^ long(binascii.hexlify(derivedhalf1), 16)))
    pub = privtopub(priv)
    if compressed:
        pub = encode_pubkey(pub,'hex_compressed')
        wif = encode_privkey(priv,'wif_compressed')
    else:
        wif = encode_privkey(priv,'wif')
    addr = pubtoaddr(pub)
    if hashlib.sha256(hashlib.sha256(addr).digest()).digest()[0:4] != addresshash:
        print('Addresshash verification failed! Password is likely incorrect.')
    return wif
Пример #27
0
def decode_address_multichain(address):
    if possible_address(address):
        raw = base58.b58decode(address, None)
        # if len(raw) < 25:
        #     raw = ('\0' * (25 - len(raw))) + raw

        #print "base58 decoded len = {}".format(len(raw))
        raw = raw[:-4] # drop checksum
        #print "no checksum        = {} ".format(len(raw))
        n = len(raw)
        skip = n - 20
        #print "skip num raw     = {} ".format(skip)
        i =0
        resulthash = '' #bytearray()
        resultversion = ''
        while i<n:
            if skip>0 and i % 6 == 0:
                skip = skip - 1
                resultversion += raw[i]
            else:
                resulthash += raw[i]
            i = i + 1
        #print "ripemd length = {}, hex = {}".format(len(resulthash), long_hex(resulthash))
        return resultversion, resulthash
    return None, None
Пример #28
0
def user_user2_threshold(user_pub, user2_pub):
    from cryptoconditions import ThresholdSha256, Ed25519Sha256
    user_pub_keys = [user_pub, user2_pub]
    threshold = ThresholdSha256(threshold=len(user_pub_keys))
    for user_pub in user_pub_keys:
        threshold.add_subfulfillment(
            Ed25519Sha256(public_key=b58decode(user_pub)))
    return threshold
Пример #29
0
def decode_check_address_multichain(address):
    version, hash = decode_address_multichain(address)
    if version is not None and hash is not None:
        raw = base58.b58decode(address, None)
        checksum = raw[-4:0]
        if hash_to_address_multichain(version, hash, checksum):
            return version, hash
    return None, None
Пример #30
0
def to_bytes(proto, string):
    # the address is a base58-encoded string
    if six.PY2 and isinstance(string, unicode):
        string = string.encode("ascii")
    mm = base58.b58decode(string)
    if len(mm) < 5:
        raise ValueError("P2P MultiHash too short: len() < 5")
    return mm
Пример #31
0
def base58decode(i):
    return base58.b58decode(str(i)).decode()
Пример #32
0
    return set([x['account_id'] for x in nodes[0].get_status()['validators']])


def get_stakes():
    return [
        int(nodes[2].get_account("test%s" % i)['result']['locked'])
        for i in range(3)
    ]


status = nodes[2].get_status()
hash_ = status['sync_info']['latest_block_hash']

tx = sign_staking_tx(nodes[2].signer_key, nodes[2].validator_key,
                     100000000000000000000000000, 2,
                     base58.b58decode(hash_.encode('utf8')))
nodes[0].send_tx(tx)

max_height = 0

print("Initial stakes: %s" % get_stakes())

while True:
    assert time.time() - started < TIMEOUT

    status = nodes[0].get_status()
    height = status['sync_info']['latest_block_height']

    if 'test2' in get_validators():
        print("Normalin, normalin")
        assert 20 <= height <= 25
Пример #33
0
def test_changes_with_new_account_with_access_key():
    """
    Plan:
    1. Create a new account with an access key.
    2. Observe the changes in the block where the receipt lands.
    3. Remove the access key.
    4. Observe the changes in the block where the receipt lands.
    """

    # re-use the key as a new account access key
    new_key = Key(
        account_id='rpc_key_value_changes_full_access',
        pk=nodes[1].signer_key.pk,
        sk=nodes[1].signer_key.sk,
    )

    # Step 1
    status = nodes[0].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    create_account_tx = transaction.sign_create_account_with_full_access_key_and_balance_tx(
        creator_key=nodes[0].signer_key,
        new_account_id=new_key.account_id,
        new_key=new_key,
        balance=10**24,
        nonce=7,
        block_hash=base58.b58decode(latest_block_hash.encode('utf8')))
    new_account_response = nodes[0].send_tx_and_wait(create_account_tx, 10)

    # Step 2
    block_hash = new_account_response['result']['receipts_outcome'][0][
        'block_hash']
    assert_changes_in_block_response(request={"block_id": block_hash},
                                     expected_response={
                                         "block_hash":
                                         block_hash,
                                         "changes": [{
                                             "type":
                                             "account_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }, {
                                             "type":
                                             "access_key_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "all_access_key_changes",
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id.
        {
            **base_request, "account_ids": [new_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix.
        {
            **base_request, "account_ids": [new_key.account_id + '_extra']
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    block_header = nodes[0].get_block(block_hash)['result']['header']
    prev_block_header = nodes[0].get_block(
        block_header['prev_hash'])['result']['header']
    nonce = prev_block_header['height'] * 1000000
    expected_response = {
        "block_hash":
        block_hash,
        "changes": [{
            "cause": {
                "type":
                "receipt_processing",
                "receipt_hash":
                new_account_response["result"]["receipts_outcome"][0]["id"],
            },
            "type": "access_key_update",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
                "access_key": {
                    "nonce": nonce,
                    "permission": "FullAccess"
                },
            }
        }]
    }
    for request in [
        {
            "block_id": block_hash,
            "changes_type": "all_access_key_changes",
            "account_ids": [new_key.account_id],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "all_access_key_changes",
            "account_ids": [
                new_key.account_id + '_non_existing1', new_key.account_id,
                new_key.account_id + '_non_existing2'
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response=expected_response)

    # Step 3
    status = nodes[0].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    nonce += 8
    delete_access_key_tx = transaction.sign_delete_access_key_tx(
        signer_key=new_key,
        target_account_id=new_key.account_id,
        key_for_deletion=new_key,
        nonce=nonce,
        block_hash=base58.b58decode(latest_block_hash.encode('utf8')))
    delete_access_key_response = nodes[1].send_tx_and_wait(
        delete_access_key_tx, 10)

    # Step 4
    block_hash = delete_access_key_response['result']['receipts_outcome'][0][
        'block_hash']
    assert_changes_in_block_response(request={"block_id": block_hash},
                                     expected_response={
                                         "block_hash":
                                         block_hash,
                                         "changes": [{
                                             "type":
                                             "account_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }, {
                                             "type":
                                             "access_key_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "all_access_key_changes",
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id
        {
            **base_request, "account_ids": [new_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix
        {
            **base_request, "account_ids": [new_key.account_id + '_extra']
        },
            # Test empty keys in single_access_key_changes request
        {
            "block_id": block_hash,
            "changes_type": "single_access_key_changes",
            "keys": []
        },
            # Test non-existing account_id
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id + '_non_existing1',
                    "public_key": new_key.pk
                },
            ],
        },
            # Test non-existing public_key for an existing account_id
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id,
                    "public_key": new_key.pk[:-3] + 'aaa'
                },
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    expected_response = {
        "block_hash":
        block_hash,
        "changes": [{
            "cause": {
                'type':
                'transaction_processing',
                'tx_hash':
                delete_access_key_response['result']['transaction']['hash'],
            },
            "type": "access_key_update",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
                "access_key": {
                    "nonce": nonce,
                    "permission": "FullAccess"
                },
            }
        }, {
            "cause": {
                "type":
                "receipt_processing",
                "receipt_hash":
                delete_access_key_response["result"]["receipts_outcome"][0]
                ["id"]
            },
            "type": "access_key_deletion",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
            }
        }]
    }

    for request in [
        {
            "block_id": block_hash,
            "changes_type": "all_access_key_changes",
            "account_ids": [new_key.account_id],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "all_access_key_changes",
            "account_ids": [
                new_key.account_id + '_non_existing1', new_key.account_id,
                new_key.account_id + '_non_existing2'
            ],
        },
        {
            "block_id": block_hash,
            "changes_type": "single_access_key_changes",
            "keys": [{
                "account_id": new_key.account_id,
                "public_key": new_key.pk
            }],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id + '_non_existing1',
                    "public_key": new_key.pk
                },
                {
                    "account_id": new_key.account_id,
                    "public_key": new_key.pk
                },
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response=expected_response)
Пример #34
0
def decode_address(addr):
    bytes = base58.b58decode(addr, None)
    if len(bytes) < 25:
        bytes = ('\0' * (25 - len(bytes))) + bytes
    return bytes[:-24], bytes[-24:-4]
Пример #35
0
def b58_to_bytes(message: str) -> bytes:
    from base58 import b58decode

    return b58decode(message)
Пример #36
0
 def test_generate_key_pair(self):
     sk_b58, vk_b58 = ed25519_generate_key_pair()
     assert len(base58.b58decode(sk_b58)) == 32
     assert len(base58.b58decode(vk_b58)) == 32
     assert SigningKey(sk_b58).encode() == sk_b58
     assert VerifyingKey(vk_b58).encode() == vk_b58
Пример #37
0
 def sign(self, sData):
     if not self.privateKey:
         raise MissingPrivateKeyException('Private key required')
     return bytes2str(sign(self.privateKey, base58.b58decode(sData)))
Пример #38
0
def validate_light_client_block(last_known_block,
                                new_block,
                                block_producers_map,
                                panic=False):
    new_block_hash = compute_block_hash(new_block['inner_lite'],
                                        new_block['inner_rest_hash'],
                                        new_block['prev_block_hash'])
    next_block_hash_decoded = combine_hash(
        base58.b58decode(new_block['next_block_inner_hash']),
        base58.b58decode(new_block_hash))

    if new_block['inner_lite']['epoch_id'] not in [
            last_known_block['inner_lite']['epoch_id'],
            last_known_block['inner_lite']['next_epoch_id']
    ]:
        if panic:
            assert False
        return False

    block_producers = block_producers_map[new_block['inner_lite']['epoch_id']]
    if len(new_block['approvals_after_next']) != len(block_producers):
        if panic:
            assert False
        return False

    total_stake = 0
    approved_stake = 0

    for approval, stake in zip(new_block['approvals_after_next'],
                               block_producers):
        total_stake += int(stake['stake'])

        if approval is None:
            continue

        approved_stake += int(stake['stake'])

        public_key = stake['public_key']

        signature = base58.b58decode(approval[len(ED_PREFIX):])
        verify_key = nacl.signing.VerifyKey(
            base58.b58decode(public_key[len(ED_PREFIX):]))

        approval_message = bytearray()
        approval_message.append(0)
        approval_message += next_block_hash_decoded
        approval_message.append(new_block['inner_lite']['height'] + 2)
        for i in range(7):
            approval_message.append(0)
        approval_message = bytes(approval_message)
        verify_key.verify(approval_message, signature)

    threshold = total_stake * 2 // 3
    if approved_stake <= threshold:
        if panic:
            assert False
        return False

    if new_block['inner_lite']['epoch_id'] == last_known_block['inner_lite'][
            'next_epoch_id']:
        if new_block['next_bps'] is None:
            if panic:
                assert False
            return False

        print(new_block['next_bps'])
        serialized_next_bp = bytearray()
        serialized_next_bp.append(len(new_block['next_bps']))
        for i in range(3):
            serialized_next_bp.append(0)
        for bp in new_block['next_bps']:
            version = 0
            if 'validator_stake_struct_version' in bp:
                # version of ValidatorStake enum
                version = int(bp['validator_stake_struct_version'][1:]) - 1
                serialized_next_bp.append(version)
            serialized_next_bp.append(5)
            for i in range(3):
                serialized_next_bp.append(0)
            serialized_next_bp += bp['account_id'].encode('utf-8')
            serialized_next_bp.append(0)  # public key type
            serialized_next_bp += base58.b58decode(
                bp['public_key'][len(ED_PREFIX):])
            stake = int(bp['stake'])
            for i in range(16):
                serialized_next_bp.append(stake & 255)
                stake >>= 8
            if version > 0:
                serialized_next_bp.append(1 if bp['is_chunk_only'] else 0)

        serialized_next_bp = bytes(serialized_next_bp)

        computed_hash = base58.b58encode(
            hashlib.sha256(serialized_next_bp).digest())
        if computed_hash != new_block['inner_lite']['next_bp_hash'].encode(
                'utf-8'):
            if panic:
                assert False
            return False

        block_producers_map[new_block['inner_lite']
                            ['next_epoch_id']] = new_block['next_bps']
Пример #39
0
def get_hex(b58_encoded_peer_id_str: str) -> str:
    """Converts base-58 multihash to hex representation"""
    bytes = base58.b58decode(b58_encoded_peer_id_str)
    sha256 = hashlib.sha256(bytes).digest()
    return sha256.hex()[:6]
Пример #40
0
def b58_encode():
    for i in words :
        decoded=b58.b58decode(i).hex()
        number.append(decoded)
Пример #41
0
def rotencode(importx, infilepath, outfilepath, inputformat, raw, exportx, offset):

    if importx == 'file':
    
        f = open(infilepath, 'r')
        raw = f.read()
        f.close()
        
    elif importx == 'print':
    
        raw = raw
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    inp = raw
    
    if inputformat == 'base64':
    
        iput = base64.b64decode(inp)
        
    elif inputformat == 'raw':
    
        iput = inp 
    
    elif inputformat == 'base32':
    
        iput = base64.b32decode(inp)
    
    elif inputformat == 'base16':
    
        iput = base64.b16decode(inp)
    
    elif inputformat == 'base58':
    
        iput = base58.b58decode(inp)
    
    elif inputformat == 'base85':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'hex':
    
        iput = inp.decode('hex')
    
    elif inputformat == 'dec':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'octal':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'binary':
    
        iput = text_from_bits(inp)
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    output = rot_alpha_encode(offset)(iput)

    if exportx == 'file':
    
        f = open(outfilepath, 'w')
        f.write(output)
        f.close()
        return True
        
    elif exportx == 'print':
    
        return output
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Пример #42
0
k = ecdsa_ssl.KEY()
k.generate(('%064x' % PRIVATE_KEY).decode('hex'))
k.set_compressed(True)

#here we retrieve the public key data generated from the supplied private key
pubkey_data = k.get_pubkey()
#then we create a signature over the hash of the signature-less transaction
sig_data = k.sign(hash_scriptless)
#a one byte "hash type" is appended to the end of the signature (https://en.bitcoin.it/wiki/OP_CHECKSIG)
sig_data = sig_data + chr(SIGHASH_ALL)

#let's check that the provided private key can actually redeem the output in question
if (bc_address_to_hash_160(public_key_to_bc_address(pubkey_data)) !=
        tx_info['txOut'][OUTPUT_INDEX]['scriptPubKey'][3:-2]):
    bytes = b58decode(SEND_TO_ADDRESS, 25)
    raise RuntimeError, "The supplied private key cannot be used to redeem output index %d\nYou need to supply the private key for address %s" % \
                            (OUTPUT_INDEX, hash_160_to_bc_address(tx_info['txOut'][OUTPUT_INDEX]['scriptPubKey'][3:-2], bytes[0]))

##now we begin creating the final transaction. this is a duplicate of the signature-less transaction,
## with the scriptSig filled out with a script that pushes the signature plus one-byte hash code type, and public key from above, to the stack

final_tx = BCDataStream()
final_tx.write_int32(tx_fields['version'])
final_tx.write_compact_size(tx_fields['num_txin'])
final_tx.write(tx_fields['prevout_hash'])
final_tx.write_uint32(tx_fields['output_index'])

##now we need to write the actual scriptSig.
## this consists of the DER-encoded values r and s from the signature, a one-byte hash code type, and the public key in uncompressed format
## we also need to prepend the length of these two data pieces (encoded as a single byte
Пример #43
0
def base58decodedInt(i):
    try:
        return int(base58.b58decode(str(i)).decode())
    except Exception as ex:
        raise AttributeError from ex
Пример #44
0
 def update_idr_cache_and_ts_revoc_store(self, stateRoot, ppTime):
     stateRoot = base58.b58decode(stateRoot.encode())
     self.idrCache.onBatchCommitted(stateRoot)
     self.tsRevoc_store.set(ppTime, stateRoot)
Пример #45
0
 def decoded_sk(self):
     key = self.sk.split(':')[1] if ':' in self.sk else self.sk
     return base58.b58decode(key.encode('ascii'))
Пример #46
0

nodes = start_cluster(
    2, 0, 1, None,
    [["epoch_length", 1000], ["block_producer_kickout_threshold", 80]], {}
)

# deploy a smart contract for testing
contract_key = nodes[0].signer_key
hello_smart_contract = load_binary_file('../tests/hello.wasm')

status = nodes[0].get_status()
latest_block_hash = status['sync_info']['latest_block_hash']
deploy_contract_tx = transaction.sign_deploy_contract_tx(
    contract_key, hello_smart_contract, 10,
    base58.b58decode(latest_block_hash.encode('utf8')))
deploy_contract_response = nodes[0].send_tx_and_wait(deploy_contract_tx, 15)
assert 'error' not in deploy_contract_response, deploy_contract_response


def check_transaction_outcome_proof(should_succeed, nonce):
    status = nodes[1].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    function_caller_key = nodes[0].signer_key
    gas = 10000000000000000 if should_succeed else 1000

    function_call_1_tx = transaction.sign_function_call_tx(
        function_caller_key, contract_key.account_id, 'setKeyValue',
        json.dumps({
            "key": "my_key",
            "value": "my_value"
Пример #47
0
def wifToPrvHex(wif):
    byte_str = binascii.hexlify(base58.b58decode(wif))
    byte_str_drop_last_4bytes = byte_str[0:-8]
    byte_str_drop_first_byte = byte_str_drop_last_4bytes[2:].decode()
    return byte_str_drop_first_byte if len(
        byte_str_drop_first_byte) == 64 else byte_str_drop_first_byte[:-2]
Пример #48
0
 def commit(self, txnCount, stateRoot, txnRoot) -> List:
     r = super().commit(txnCount, stateRoot, txnRoot)
     stateRoot = base58.b58decode(stateRoot.encode())
     self.idrCache.onBatchCommitted(stateRoot)
     return r
Пример #49
0
def sign(privateKey, message):
    random64 = os.urandom(64)

    return base58.b58encode(
        curve.calculateSignature(random64, base58.b58decode(privateKey),
                                 message))
Пример #50
0
def Base58Decoder(text):
    print('[+] Base58 decoded.')
    return base58.b58decode(text)
Пример #51
0
 def parse_public_key(data):
     data = str(data[3:])
     decoded = b58decode(data)
     decoded = decoded[:-4]
     return decoded
Пример #52
0
    async def fetch_data(self, url, session):
        try:
            async with session.get(url) as response:
                data = await response.text()
                data = pjson.loads(data)
                cnfy_id = 'cnfy-{}'.format(str(uuid.uuid4()))

                for tx in data['transactions']:
                    if tx['type'] in [
                            4
                    ] and tx['feeAssetId'] == config['blockchain']['asset_id']:

                        attachment_base58 = base58.b58decode(
                            tx['attachment']).decode('utf-8')
                        attachment = requests.get('{0}:{1}/ipfs/{2}'.format(
                            config['ipfs']['host'], config['ipfs']['get_port'],
                            attachment_base58)).text
                        attachment_hash = hashlib.sha256(
                            attachment.encode('utf-8')).hexdigest()

                        root = ET.fromstring(attachment)
                        version = root.findall('version')[0].text if len(
                            root.findall('version')) > 0 else None
                        blockchain = root.findall('blockchain')[0].text if len(
                            root.findall('blockchain')) > 0 else None
                        network = root.findall('network')[0].text if len(
                            root.findall('network')) > 0 else None
                        messages = root.findall('messages')[0] if len(
                            root.findall('messages')) > 0 else []

                        # members = [tx['senderPublicKey']]
                        # for message in messages:
                        #     to_public_key = None
                        #     to = message.findall('to')[0] if len(message.findall('to')) > 0 else None
                        #     if to:
                        #         to_public_key = to.findall('publickey')[0].text if len(to.findall('publickey')) > 0 else None
                        #     if to_public_key and to_public_key not in members:
                        #         members.append(to_public_key)

                        #     cc_public_key = None
                        #     cc = message.findall('cc')[0] if len(message.findall('cc')) > 0 else None
                        #     if cc:
                        #         cc_public_key = cc.findall('publickey')[0].text if len(cc.findall('publickey')) > 0 else None
                        #     if cc_public_key and cc_public_key not in members:
                        #         members.append(cc_public_key)

                        # group_hash = hashlib.sha256(''.join(sorted(members)).encode('utf-8')).hexdigest()
                        for message in messages:
                            to_public_key = None
                            cc_public_key = None
                            to = message.findall('to')[0] if len(
                                message.findall('to')) > 0 else None
                            cc = message.findall('cc')[0] if len(
                                message.findall('cc')) > 0 else None
                            if to:
                                to_public_key = to.findall(
                                    'publickey')[0].text if len(
                                        to.findall('publickey')) > 0 else None
                            if cc:
                                cc_public_key = cc.findall(
                                    'publickey')[0].text if len(
                                        cc.findall('publickey')) > 0 else None

                            subject_ciphertext = None
                            subject_sha256hash = None
                            subject = message.findall('subject')[0] if len(
                                message.findall('subject')) > 0 else None
                            if subject:
                                subject_ciphertext = subject.findall(
                                    'ciphertext')[0].text if len(
                                        subject.findall(
                                            'ciphertext')) > 0 else None
                                subject_sha256hash = subject.findall(
                                    'sha256'
                                )[0].text if len(
                                    subject.findall('sha256')) > 0 else None

                            body_ciphertext = None
                            body_sha256hash = None
                            body = message.findall('body')[0] if len(
                                message.findall('body')) > 0 else None
                            if body:
                                body_ciphertext = body.findall(
                                    'ciphertext'
                                )[0].text if len(
                                    body.findall('ciphertext')) > 0 else None
                                body_sha256hash = body.findall(
                                    'sha256')[0].text if len(
                                        body.findall('sha256')) > 0 else None

                            recipient_public_key = to_public_key if to_public_key else cc_public_key
                            recipient_type = 'to' if to_public_key else 'cc'

                            group_hash = hashlib.sha256(''.join([
                                subject_sha256hash or '', body_sha256hash or ''
                            ]).encode('utf-8')).hexdigest()
                            extra = message.findall('extra')[0] if len(
                                message.findall('extra')) > 0 else None
                            if extra:
                                group_hash = extra.findall(
                                    'groupHash'
                                )[0].text if len(
                                    extra.findall('groupHash')) > 0 else None

                            cdm_id = 'cdm-' + str(uuid.uuid4())
                            self.sql_data_cdms.append(
                                (cdm_id, tx['id'], recipient_public_key,
                                 subject_ciphertext, subject_sha256hash,
                                 body_ciphertext, body_sha256hash, group_hash,
                                 blockchain, network, recipient_type))

                            senders = message.findall('from')[0] if len(
                                message.findall('from')) > 0 else None
                            if senders:
                                for sender in senders:
                                    sender_public_key = sender.findall(
                                        'publickey')[0].text if len(
                                            sender.findall(
                                                'publickey')) > 0 else None
                                    signature = sender.findall(
                                        'signature')[0].text if len(
                                            sender.findall(
                                                'signature')) > 0 else None

                                    sender_id = str(uuid.uuid4())
                                    self.sql_data_senders.append(
                                        (sender_id, cdm_id, sender_public_key,
                                         signature, True))

                        tx_data = (tx['id'], data['height'], tx['type'],
                                   tx['sender'], tx['senderPublicKey'],
                                   tx['recipient'], tx['amount'],
                                   tx['assetId'], tx['feeAssetId'],
                                   tx['feeAsset'], tx['fee'], tx['attachment'],
                                   tx['version'],
                                   datetime.fromtimestamp(tx['timestamp'] /
                                                          1e3), cnfy_id,
                                   attachment_hash, attachment)

                        self.sql_data_transactions.append(tx_data)

                        for proof in tx['proofs']:
                            self.sql_data_proofs.append((tx['id'], proof))

        except asyncio.CancelledError:
            logger.info('Parser has been stopped')
            raise
        except Exception as error:
            logger.error('Fetching data error: {}'.format(error))
            pass
Пример #53
0
def test_key_value_changes():
    """
    Plan:
    1. Deploy a contract.
    2. Observe the code changes in the block where the transaction outcome "lands".
    3. Send two transactions to be included into the same block setting and overriding the value of
       the same key (`my_key`).
    4. Observe the changes in the block where the transaction outcome "lands".
    """

    contract_key = nodes[0].signer_key
    hello_smart_contract = load_binary_file('../tests/hello.wasm')

    # Step 1
    status = nodes[0].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    deploy_contract_tx = transaction.sign_deploy_contract_tx(
        contract_key, hello_smart_contract, 10,
        base58.b58decode(latest_block_hash.encode('utf8')))
    deploy_contract_response = nodes[0].send_tx_and_wait(
        deploy_contract_tx, 10)

    # Step 2
    block_hash = deploy_contract_response['result']['transaction_outcome'][
        'block_hash']
    assert_changes_in_block_response(request={"block_id": block_hash},
                                     expected_response={
                                         "block_hash":
                                         block_hash,
                                         "changes": [{
                                             "type":
                                             "account_touched",
                                             "account_id":
                                             contract_key.account_id,
                                         }, {
                                             "type":
                                             "contract_code_touched",
                                             "account_id":
                                             contract_key.account_id,
                                         }, {
                                             "type":
                                             "access_key_touched",
                                             "account_id":
                                             contract_key.account_id,
                                         }]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "contract_code_changes",
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id
        {
            **base_request, "account_ids": [contract_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix
        {
            **base_request, "account_ids":
            [contract_key.account_id + '_extra']
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    expected_response = {
        "block_hash":
        block_hash,
        "changes": [
            {
                "cause": {
                    "type":
                    "receipt_processing",
                    "receipt_hash":
                    deploy_contract_response["result"]["receipts_outcome"][0]
                    ["id"],
                },
                "type": "contract_code_update",
                "change": {
                    "account_id":
                    contract_key.account_id,
                    "code_base64":
                    base64.b64encode(hello_smart_contract).decode('utf-8'),
                }
            },
        ]
    }
    base_request = {
        "block_id": block_hash,
        "changes_type": "contract_code_changes",
    }
    for request in [
        {
            **base_request, "account_ids": [contract_key.account_id]
        },
        {
            **base_request, "account_ids": [
                contract_key.account_id + '_non_existing1',
                contract_key.account_id,
                contract_key.account_id + '_non_existing2'
            ]
        },
    ]:
        assert_changes_response(request=request,
                                expected_response=expected_response)

    # Step 3
    status = nodes[1].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    function_caller_key = nodes[0].signer_key

    def set_value_1():
        function_call_1_tx = transaction.sign_function_call_tx(
            function_caller_key, contract_key.account_id, 'setKeyValue',
            json.dumps({
                "key": "my_key",
                "value": "my_value_1"
            }).encode('utf-8'), 300000000000000, 100000000000, 20,
            base58.b58decode(latest_block_hash.encode('utf8')))
        nodes[1].send_tx_and_wait(function_call_1_tx, 10)

    function_call_1_thread = threading.Thread(target=set_value_1)
    function_call_1_thread.start()

    function_call_2_tx = transaction.sign_function_call_tx(
        function_caller_key, contract_key.account_id, 'setKeyValue',
        json.dumps({
            "key": "my_key",
            "value": "my_value_2"
        }).encode('utf-8'), 300000000000000, 100000000000, 30,
        base58.b58decode(latest_block_hash.encode('utf8')))
    function_call_2_response = nodes[1].send_tx_and_wait(
        function_call_2_tx, 10)
    assert function_call_2_response['result']['receipts_outcome'][0]['outcome']['status'] == {'SuccessValue': ''}, \
        "Expected successful execution, but the output was: %s" % function_call_2_response
    function_call_1_thread.join()

    tx_block_hash = function_call_2_response['result']['transaction_outcome'][
        'block_hash']

    # Step 4
    assert_changes_in_block_response(request={"block_id": tx_block_hash},
                                     expected_response={
                                         "block_hash":
                                         tx_block_hash,
                                         "changes": [
                                             {
                                                 "type":
                                                 "account_touched",
                                                 "account_id":
                                                 contract_key.account_id,
                                             },
                                             {
                                                 "type":
                                                 "access_key_touched",
                                                 "account_id":
                                                 contract_key.account_id,
                                             },
                                             {
                                                 "type":
                                                 "data_touched",
                                                 "account_id":
                                                 contract_key.account_id,
                                             },
                                         ]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "data_changes",
        "key_prefix_base64": base64.b64encode(b"my_key").decode('utf-8'),
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id
        {
            **base_request, "account_ids": [contract_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix
        {
            **base_request, "account_ids":
            [contract_key.account_id + '_extra']
        },
            # Test non-existing key prefix
        {
            **base_request,
            "account_ids": [contract_key.account_id],
            "key_prefix_base64":
            base64.b64encode(b"my_key_with_extra").decode('utf-8'),
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    expected_response = {
        "block_hash":
        tx_block_hash,
        "changes": [{
            "cause": {
                "type": "receipt_processing",
            },
            "type": "data_update",
            "change": {
                "account_id": contract_key.account_id,
                "key_base64": base64.b64encode(b"my_key").decode('utf-8'),
                "value_base64":
                base64.b64encode(b"my_value_1").decode('utf-8'),
            }
        }, {
            "cause": {
                "type":
                "receipt_processing",
                "receipt_hash":
                function_call_2_response["result"]["receipts_outcome"][0]
                ["id"],
            },
            "type": "data_update",
            "change": {
                "account_id": contract_key.account_id,
                "key_base64": base64.b64encode(b"my_key").decode('utf-8'),
                "value_base64":
                base64.b64encode(b"my_value_2").decode('utf-8'),
            }
        }]
    }

    base_request = {
        "block_id": tx_block_hash,
        "changes_type": "data_changes",
        "key_prefix_base64": base64.b64encode(b"my_key").decode('utf-8'),
    }
    for request in [
        {
            **base_request, "account_ids": [contract_key.account_id]
        },
        {
            **base_request, "account_ids": [
                contract_key.account_id + '_non_existing1',
                contract_key.account_id,
                contract_key.account_id + '_non_existing2'
            ]
        },
        {
            **base_request,
            "account_ids": [contract_key.account_id],
            "key_prefix_base64": base64.b64encode(b"").decode('utf-8'),
        },
        {
            **base_request,
            "account_ids": [contract_key.account_id],
            "key_prefix_base64": base64.b64encode(b"my_ke").decode('utf-8'),
        },
    ]:
        assert_changes_response(
            request=request,
            expected_response=expected_response,
            exclude_paths={"root['changes'][0]['cause']['receipt_hash']"},
        )
Пример #54
0
def encryptDes(destype, importx, impfilepath, export, filepath, outputformat, ivtype, iv, passwd, raw, keyimport):


    if keyimport == 'base64':
    
        key = base64.b64decode(passwd)
    
    elif keyimport == 'base32':
    
        key = base64.b32decode(passwd)
    
    elif keyimport == 'base16':
    
        key = base64.b16decode(passwd)
    
    elif keyimport == 'base58':
    
        key = base58.b58decode(passwd)
    
    elif keyimport == 'base85':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif keyimport == 'hex':
    
        key = passwd.decode('hex')
    
    elif keyimport == 'dec':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif keyimport == 'octal':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif keyimport == 'binary':
    
        key = text_from_bits(passwd)
        
    elif keyimport == 'raw':
    
        key = passwd 
               
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        

    if importx == 'file':
    
        f = open(impfilepath, 'r')
        raw = f.read()
        f.close()
        
    elif importx == 'print':
    
        raw = raw
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    raw = pad(raw)
    
    if len(passwd) == 8:
    
        key = passwd
            
    else:
        
        print('\033[1;31m[-]\033[0m DES Key must be 8 bytes long')

    if ivtype == 'randomstart':
    
        iv = Random.new().read(DES.block_size)
        sadd = iv
        eadd = ''
    
    elif ivtype == 'randomend':
    
        iv = Random.new().read(DES.block_size)
        sadd = ''
        eadd = iv
    
    elif ivtype == 'custom':
    
        iv = iv
        sadd = iv
        eadd = ''
    
    elif ivtype == 'noiv':
    
        sadd = ''
        eadd = ''
    
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if destype == 'ecb':
        
        cipher = DES.new(key, DES.MODE_ECB)
    
    
    elif destype == 'cbc':
    
        cipher = DES.new(key, DES.MODE_CBC, iv)
        
    elif destype == 'ofb':
    
        cipher = DES.new(key, DES.MODE_OFB, iv)
    
    elif destype == 'ocb':
    
        cipher = DES.new(key, DES.MODE_OCB, iv)
    
    elif destype == 'ctr':
    
        cipher = DES.new(key, DES.MODE_CTR)
    
    elif destype == 'cfb':
    
        cipher = DES.new(key, DES.MODE_CFB, iv)
    
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    out = cipher.encrypt(raw)
    
    out = sadd + out + eadd
        
    if outputformat == 'base64':
    
        output = base64.b64encode(out)
        
    elif outputformat == 'raw':
    
        output = out 
    
    elif outputformat == 'base32':
    
        output = base64.b32encode(out)
    
    elif outputformat == 'base16':
    
        output = base64.b16encode(out)
    
    elif outputformat == 'base58':
    
        output = base58.b58encode(out)
    
    elif outputformat == 'base85':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif outputformat == 'hex':
    
        output = out.encode('hex')
    
    elif outputformat == 'dec':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif outputformat == 'octal':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif outputformat == 'binary':
    
        output = text_to_bits(out)
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    if export == 'file':
    
        filename = open(filepath, 'w')
        filename.write(output)
        filename.close()
        
        return True
        
    elif export == 'print':
    
        return output
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Пример #55
0
def check_transaction_outcome_proof(should_succeed, nonce):
    status = nodes[1].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    function_caller_key = nodes[0].signer_key
    gas = 10000000000000000 if should_succeed else 1000

    function_call_1_tx = transaction.sign_function_call_tx(
        function_caller_key, contract_key.account_id, 'setKeyValue',
        json.dumps({
            "key": "my_key",
            "value": "my_value"
        }).encode('utf-8'), gas, 100000000000, nonce,
        base58.b58decode(latest_block_hash.encode('utf8')))
    function_call_result = nodes[1].send_tx_and_wait(function_call_1_tx, 15)
    assert 'error' not in function_call_result

    status = nodes[0].get_status()
    latest_block_height = status['sync_info']['latest_block_height']

    # wait for finalization
    light_client_request_block_hash = None
    while True:
        status = nodes[0].get_status()
        cur_height = status['sync_info']['latest_block_height']
        if cur_height > latest_block_height + 2 and light_client_request_block_hash is None:
            light_client_request_block_hash = status['sync_info']['latest_block_hash']
        if cur_height > latest_block_height + 7:
            break
        time.sleep(1)

    light_client_block = nodes[0].json_rpc('next_light_client_block', [light_client_request_block_hash])['result']
    light_client_block_hash = compute_block_hash(light_client_block['inner_lite'],
                                                 light_client_block['inner_rest_hash'],
                                                 light_client_block['prev_block_hash']).decode('utf-8')

    queries = [
        {"type": "transaction", "transaction_hash": function_call_result['result']['transaction_outcome']['id'], "sender_id": "test0",
         "light_client_head": light_client_block_hash}
    ]
    outcomes = [(function_call_result['result']['transaction_outcome']['outcome'],
                 function_call_result['result']['transaction_outcome']['id'])]
    for receipt_outcome in function_call_result['result']['receipts_outcome']:
        outcomes.append((receipt_outcome['outcome'], receipt_outcome['id']))
        queries.append({"type": "receipt", "receipt_id": receipt_outcome['id'], "receiver_id": "test0",
                        "light_client_head": light_client_block_hash})

    for query, (outcome, id) in zip(queries, outcomes):
        res = nodes[0].json_rpc('EXPERIMENTAL_light_client_proof', query, timeout=10)
        assert 'error' not in res, res
        light_client_proof = res['result']
        # check that execution outcome root proof is valid
        execution_outcome_hash = hashlib.sha256(serialize_execution_outcome_with_id(outcome, id)).digest()
        outcome_root = compute_merkle_root_from_path(light_client_proof['outcome_proof']['proof'],
                                                     execution_outcome_hash)
        block_outcome_root = compute_merkle_root_from_path(light_client_proof['outcome_root_proof'],
                                                           hashlib.sha256(outcome_root).digest())
        block = nodes[0].json_rpc('block', {"block_id": light_client_proof['outcome_proof']['block_hash']})
        expected_root = block['result']['header']['outcome_root']
        assert base58.b58decode(
            expected_root) == block_outcome_root, f'expected outcome root {expected_root} actual {base58.b58encode(block_outcome_root)}'
        # check that the light block header is valid
        block_header_lite = light_client_proof['block_header_lite']
        computed_block_hash = compute_block_hash(block_header_lite['inner_lite'], block_header_lite['inner_rest_hash'],
                                                 block_header_lite['prev_block_hash'])
        assert light_client_proof['outcome_proof']['block_hash'] == computed_block_hash.decode(
            'utf-8'), f'expected block hash {light_client_proof["outcome_proof"]["block_hash"]} actual {computed_block_hash}'
        # check that block proof is valid
        block_merkle_root = compute_merkle_root_from_path(light_client_proof['block_proof'],
                                                          light_client_proof['outcome_proof']['block_hash'])
        assert base58.b58decode(light_client_block['inner_lite'][
                                    'block_merkle_root']) == block_merkle_root, f'expected block merkle root {light_client_block["inner_lite"]["block_merkle_root"]} actual {base58.b58encode(block_merkle_root)}'
Пример #56
0
    with open('block.txt', 'r') as file:

  except:
    block_list = []

old_in = []
old_out = []
for block in block_list:
  for tx in block['tx']:
    old_in.append(tx['in'])
    old_out.append(tx['out'])

unspend = []
unused = []
for key in key_list:
  key_hex = base58.b58decode(key['public']).hex()
  if key_hex not in old_in:
    if key_hex in old_out:
      unspend.append(key)
    else:
      unused.append(key)

print(len(unspent), 'unspent keys(coints):')
for key in unspent:
  print('private:', key['private'])
  print('public :', key['public'])

print()

print(len(unused), 'used keys:')
for key in used:
Пример #57
0
def b58dc(encoded, trim=0):
    unencoded = b58decode(encoded)[:-trim]
    return unencoded
Пример #58
0
def decryptDes(destype, importx, filepath, export, expfilepath, inputformat, ivtype, iv, passwd, raw):


    if importx == 'file':
    
        f = open(filepath, 'r')
        raw = f.read()
        f.close()
        
    elif importx == 'print':
    
        raw = raw
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    inp = raw
        
    if inputformat == 'base64':
    
        iput = base64.b64decode(inp)
        
    elif inputformat == 'raw':
    
        iput = inp 
    
    elif inputformat == 'base32':
    
        iput = base64.b32decode(inp)
    
    elif inputformat == 'base16':
    
        iput = base64.b16decode(inp)
    
    elif inputformat == 'base58':
    
        iput = base58.b58decode(inp)
    
    elif inputformat == 'base85':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'hex':
    
        iput = inp.decode('hex')
    
    elif inputformat == 'dec':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'octal':
    
        print('\033[1;31m[-]\033[0m Option not available yet')
    
    elif inputformat == 'binary':
    
        iput = text_from_bits(inp)
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    if len(passwd) == 8:
    
        key = passwd
            
    else:
        
        print('\033[1;31m[-]\033[0m DES Key must be 8 bytes long')

    if ivtype == 'randomstart':
    
        iv = iput[:8]
        iput = iput[8:]
    
    elif ivtype == 'randomend':
    
        iv = iput[-8:]
        iput = iput[:-8]
    
    elif ivtype == 'custom':
    
        iv = iv
        iput = iput
    
    elif ivtype == 'noiv':
    
        iv = ''
        iput = iput
    
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    if destype == 'ecb':
        
        cipher = DES.new(key, DES.MODE_ECB)
        
    elif destype == 'ofb':
    
        cipher = DES.new(key, DES.MODE_OFB, iv)
    
    
    elif destype == 'cbc':
    
        cipher = DES.new(key, DES.MODE_CBC, iv)
    
    elif destype == 'ocb':
    
        cipher = DES.new(key, DES.MODE_OCB, iv)
    
    elif destype == 'ctr':
    
        cipher = DES.new(key, DES.MODE_CTR)
    
    elif destype == 'cfb':
    
        cipher = DES.new(key, DES.MODE_CFB, iv)
    
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
        
    out = cipher.decrypt(iput)
    
    out = unpad(out)
    
    if export == 'file':
    
        filename = open(expfilepath, 'w')
        filename.write(out)
        filename.close()
        
        return True
        
    elif export == 'print':
    
        return out
        
    else:
    
        print('\033[1;31m[-]\033[0m Unknown error.')
        return False
Пример #59
0
#!/usr/bin/env python3
import base64
import base58
import base62

s = 'O53GG4CSJRHEWQT2GJ5HC4CGOM4VKY3SOZGECZ2YNJTXO6LROV3DIR3CK4ZEMWCDHFMTOWSXGRSHU23DLJVTS5BXOQZXMU3ONJSFKRCVO5BEGVSELJSGUNSYLI2XQ32UOI3FKWDYMJQWOMKQOJ4XIU2WN5KTKWT2INUW44SZONGUUN2BMFRTQQJYKM3WGSSUNVXGEU3THFIFUSDHIVWVEQ3LJVUXEMSXK5MXSZ3TG5JXORKTMZRFIVQ='
print(s)

s = base64.b32decode(s)
print(s)

s = base58.b58decode(s)
print(s)

s = base62.decodebytes(bytes.decode(s))
print(s)

s = base64.b64decode(s)

print(s)

s = base64.a85decode(s)
print(s)

Пример #60
0
def main():
    node_root = "/tmp/near/upgradable"
    if os.path.exists(node_root):
        shutil.rmtree(node_root)
    subprocess.check_output('mkdir -p /tmp/near', shell=True)

    branch = branches.latest_rc_branch()
    print(f"Latest rc release branch is {branch}")
    near_root, (stable_branch,
                current_branch) = branches.prepare_ab_test(branch)

    # Setup local network.
    print([
        "%snear-%s" % (near_root, stable_branch),
        "--home=%s" % node_root, "testnet", "--v", "4", "--prefix", "test"
    ])
    subprocess.call([
        "%snear-%s" % (near_root, stable_branch),
        "--home=%s" % node_root, "testnet", "--v", "4", "--prefix", "test"
    ])
    genesis_config_changes = [("epoch_length", 20),
                              ("num_block_producer_seats", 10),
                              ("num_block_producer_seats_per_shard", [10]),
                              ("block_producer_kickout_threshold", 80),
                              ("chunk_producer_kickout_threshold", 80),
                              ("chain_id", "testnet")]
    node_dirs = [os.path.join(node_root, 'test%d' % i) for i in range(4)]
    for i, node_dir in enumerate(node_dirs):
        cluster.apply_genesis_changes(node_dir, genesis_config_changes)

    # Start 3 stable nodes and one current node.
    config = {
        "local": True,
        'near_root': near_root,
        'binary_name': "near-%s" % stable_branch
    }
    nodes = [
        cluster.spin_up_node(config, near_root, node_dirs[0], 0, None, None)
    ]
    for i in range(1, 3):
        nodes.append(
            cluster.spin_up_node(config, near_root, node_dirs[i], i,
                                 nodes[0].node_key.pk, nodes[0].addr()))
    if os.getenv('NAYDUCK'):
        config["binary_name"] = "near"
    else:
        config["binary_name"] = "near-%s" % current_branch
    nodes.append(
        cluster.spin_up_node(config, near_root, node_dirs[3], 3,
                             nodes[0].node_key.pk, nodes[0].addr()))

    time.sleep(2)

    # deploy a contract
    status = nodes[0].get_status()
    hash = status['sync_info']['latest_block_hash']
    tx = sign_deploy_contract_tx(
        nodes[0].signer_key,
        load_binary_file(
            '../runtime/near-test-contracts/res/test_contract_rs.wasm'), 1,
        base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res

    # write some random value
    tx = sign_function_call_tx(nodes[0].signer_key,
                               nodes[0].signer_key.account_id,
                               'write_random_value', [], 10**13, 0, 2,
                               base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    wait_for_blocks_or_timeout(nodes[0], 20, 120)

    # Restart stable nodes into new version.
    for i in range(3):
        nodes[i].kill()
        nodes[i].binary_name = config['binary_name']
        nodes[i].start(nodes[0].node_key.pk, nodes[0].addr())

    wait_for_blocks_or_timeout(nodes[3], 60, 120)
    status0 = nodes[0].get_status()
    status3 = nodes[3].get_status()
    protocol_version = status0['protocol_version']
    latest_protocol_version = status3["latest_protocol_version"]
    assert protocol_version == latest_protocol_version, \
        "Latest protocol version %d should match active protocol version %d" % (latest_protocol_version, protocol_version)

    hash = status0['sync_info']['latest_block_hash']

    # write some random value again
    tx = sign_function_call_tx(nodes[0].signer_key,
                               nodes[0].signer_key.account_id,
                               'write_random_value', [], 10**13, 0, 4,
                               base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    # hex_account_id = (b"I'm hex!" * 4).hex()
    hex_account_id = '49276d206865782149276d206865782149276d206865782149276d2068657821'
    tx = sign_payment_tx(key=nodes[0].signer_key,
                         to=hex_account_id,
                         amount=10**25,
                         nonce=5,
                         blockHash=base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    # Successfully created a new account on transfer to hex
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    hex_account_balance = int(
        nodes[0].get_account(hex_account_id)['result']['amount'])
    assert hex_account_balance == 10**25