示例#1
0
    def test_derive_key_data(self, sk, pk, pkh):
        public_key = Key.from_encoded_key(pk)
        self.assertFalse(public_key.is_secret)
        self.assertEqual(pk, public_key.public_key())
        self.assertEqual(pkh, public_key.public_key_hash())

        secret_key = Key.from_encoded_key(sk)
        self.assertTrue(secret_key.is_secret)
        self.assertEqual(pk, secret_key.public_key())
        self.assertEqual(sk, secret_key.secret_key())
 def to_xtz(self) -> str:
     if isinstance(self.key, (ED25519Priv, ED25519Pub)):
         if self.version == Version.PRIVATE:
             return TezosKey.from_secret_exponent(
                 self.key.get_private_bytes()).secret_key()
         else:
             return TezosKey.from_public_point(
                 self.key.get_public_bytes()).public_key_hash()
     else:
         raise ValueError("Can only derive XTZ from ED25519")
示例#3
0
    def _spawn_context(
        self,
        shell: Optional[Union[ShellQuery, str]] = None,
        key: Optional[Union[Key, str, dict]] = None,
        address: Optional[str] = None,
        block_id: Optional[Union[str, int]] = None,
        mode: Optional[str] = None,
        script: Optional[dict] = None,
        ipfs_gateway: Optional[str] = None,
    ) -> ExecutionContext:
        if isinstance(shell, str):
            if shell.endswith('.pool'):
                shell = shell.split('.')[0]
                assert shell in nodes, f'unknown network {shell}'
                shell = ShellQuery(RpcMultiNode(nodes[shell]))
            elif shell in nodes:
                shell = ShellQuery(RpcNode(nodes[shell][0]))
            else:
                shell = ShellQuery(RpcNode(shell))
        else:
            assert shell is None or isinstance(
                shell, ShellQuery), f'unexpected shell {shell}'

        if isinstance(key, str):
            if key in keys:
                key = Key.from_encoded_key(keys[key])
            elif is_public_key(key):
                key = Key.from_encoded_key(key)
            elif is_pkh(key):
                key = KeyHash(key)
            elif exists(expanduser(key)):
                key = Key.from_faucet(key)
            else:
                key = Key.from_alias(key)
        elif isinstance(key, dict):
            key = Key.from_faucet(key)
        else:
            assert key is None or isinstance(key, Key), f'unexpected key {key}'

        if isinstance(address, str):
            try:
                script = self.shell.contracts[address].script()
            except RpcError as e:
                raise RpcError(f'Contract {address} not found', *e.args) from e

        return ExecutionContext(
            shell=shell or self.context.shell,
            key=key or self.context.key,
            address=address,
            block_id=block_id,
            script=script or self.context.script,
            mode=mode or self.context.mode,
            ipfs_gateway=ipfs_gateway,
        )
示例#4
0
 def to_xtz(self) -> str:
     if isinstance(self.key, (ED25519Priv, ED25519Pub)):
         # ED25519 tz1 addresses
         if self.version == Version.PRIVATE:
             return TezosKey.from_secret_exponent(self.key.get_private_bytes(), curve = b'ed').secret_key()
         else:
             return TezosKey.from_public_point(self.key.get_public_bytes(), curve = b'ed').public_key_hash()
     elif isinstance(self.key, (Secp256k1Priv, Secp256k1Pub)):
         # Secp256k1 tz2 addresses
         if self.version == Version.PRIVATE:
             return TezosKey.from_secret_exponent(self.key.get_private_bytes(), curve = b'sp').secret_key()
         else:
             return TezosKey.from_public_point(self.key.get_public_bytes(), curve = b'sp').public_key_hash()
     else:
         raise ValueError("Can only derive XTZ from ED25519 or Secp256k1")
示例#5
0
 def __init__(self, context: Optional[ExecutionContext] = None):
     super(ContextMixin, self).__init__()
     if context is None:
         context = ExecutionContext(
             shell=ShellQuery(RpcNode(nodes[default_network][0])),
             key=Key.from_encoded_key(default_key) if is_installed() else KeyHash(default_key_hash))
     self.context = context
示例#6
0
    def test_encrypted_keys(self, sk, passphrase, salt, pk):
        key = Key.from_encoded_key(sk, passphrase=passphrase)
        self.assertEqual(pk, key.public_key())

        with patch('pytezos.crypto.key.pysodium.randombytes',
                   return_value=salt):
            self.assertEqual(sk, key.secret_key(passphrase))
示例#7
0
 def test_deterministic_signatures(self, sk, msg, sig):
     """
     See RFC6979 for explanation
     https://tools.ietf.org/html/rfc6979#section-3.2
     """
     key = Key.from_encoded_key(sk)
     signature = key.sign(msg)
     self.assertEqual(sig, signature)
示例#8
0
 def test_encrypted_key_str_password(self):
     key = Key.from_encoded_key(
         key=
         'edesk1UrFQK6xJM6SYdLxMQbyKaaYQmzYVvQRpJXUmxj3apZ1ufRu4aHSTqWrJiqcHywSbnF146wkNcpUAW7Qy6H',
         passphrase='12345')
     self.assertEqual(
         'edsk2juUM8ZMUkaCKHWVnzWhp9DxrK93YK1rQjYk3pTEq2ThXpBxkX',
         key.secret_key())
示例#9
0
 def execute(cls, stack: MichelsonStack, stdout: List[str],
             context: AbstractContext):
     a = cast(KeyType, stack.pop1())
     a.assert_type_equal(KeyType)
     key = Key.from_encoded_key(str(a))
     res = KeyHashType.from_value(key.public_key_hash())
     stack.push(res)
     stdout.append(format_stdout(cls.prim, [a], [res]))  # type: ignore
     return cls(stack_items_added=1)
示例#10
0
    def check_message(self, message: str, public_key: str, signature: str, block: str = 'genesis') -> None:
        """Check message signature

        :param message: Signed operation
        :param public_key: Signer's public key
        :param signature: Message signature
        :param block: Specify block, defaults to genesis
        """
        pk = Key.from_encoded_key(public_key)
        pk.verify(
            signature=signature,
            message=self.failing_noop(message).message(block=block),
        )
示例#11
0
 def execute(cls, stack: MichelsonStack, stdout: List[str],
             context: AbstractContext):
     pk, sig, msg = cast(Tuple[KeyType, SignatureType, BytesType],
                         stack.pop3())
     pk.assert_type_equal(KeyType)
     sig.assert_type_equal(SignatureType)
     msg.assert_type_equal(BytesType)
     key = Key.from_encoded_key(str(pk))
     try:
         key.verify(signature=str(sig), message=bytes(msg))
     except ValueError:
         res = BoolType(False)
     else:
         res = BoolType(True)
     stack.push(res)
     stdout.append(format_stdout(cls.prim, [pk, sig, msg], [res]))
     return cls()
示例#12
0
 def to_xtz(self) -> str:
     if self.version == Version.PRIVATE:
         return TezosKey.from_secret_exponent(self.key.get_private_bytes()).secret_key()
     else:
         return TezosKey.from_public_point(self.key.get_public_bytes()).public_key_hash()
示例#13
0
 def test_french_mnemonic(self):
     # Ensure that English isn't the only language supported for loading keys
     mnemonic = Mnemonic('french').generate(128)
     self.assertIsNotNone(
         Key.from_mnemonic(mnemonic, validate=True, language='french'))
示例#14
0
         'edpkuTXkJDGcFd5nh6VvMz8phXxU3Bi7h6hqgywNFi1vZTfQNnS1RV',
         '4000000000000'
     ],
     [
         'edpkuFrRoDSEbJYgxRtLx2ps82UdaYc1WwfS9sE11yhauZt5DgCHbU',
         '4000000000000'
     ],
     [
         'edpkv8EUUH68jmo3f7Um5PezmfGrRF24gnfLpH3sVNwJnV5bVCxL2n',
         '4000000000000'
     ],
 ],
 'bootstrap_contracts': [],
 'commitments': [
     [
         Key.from_faucet(sandbox_commitment).blinded_public_key_hash(),
         '100500000000',
     ],
 ],
 'preserved_cycles':
 2.0,
 'blocks_per_cycle':
 8.0,
 'blocks_per_commitment':
 4.0,
 'blocks_per_roll_snapshot':
 4.0,
 'blocks_per_voting_period':
 64.0,
 'time_between_blocks': ['0', '0'],
 'endorsers_per_block':
示例#15
0
def get_random_key():
    curve = rnd.choice([b'ed', b'sp', b'p2'])
    return Key.generate(export=False, curve=curve)
示例#16
0
 def test_regression_p256_short_sig(self):
     key = Key.from_encoded_key(
         'p2sk3xPfYsoExTVi7bGSH2KoHgpxFNqewUczHkLtQvr1bwnbhzGM9Y')
     key.sign('try25')
示例#17
0
 def test_sign_and_verify(self, sk, msg):
     key = Key.from_encoded_key(sk)
     sig = key.sign(msg)
     key.verify(sig, msg)
     self.assertRaises(ValueError, key.verify, sig, b'fake')
示例#18
0
 def test_verify_ext_signatures(self, pk, msg, sig):
     key = Key.from_encoded_key(pk)
     key.verify(sig, msg)
     self.assertRaises(ValueError, key.verify, sig, b'fake')