def test_compute_root_multiple_hashes(self):
        expected_hash = Helper.bin_dbl_sha256(
            binascii.unhexlify(b'aa' * 32 + b'bb' * 32))

        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hashes = [hash1, hash2]
        root = MerkleTree.ComputeRoot(hashes)

        self.assertEqual(expected_hash, root.ToArray())
    def test_trim_node3(self):
        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hashes = [hash1, hash2]
        m = MerkleTree(hashes)

        depth = 1
        flags = bytearray.fromhex('0000')
        m._TrimNode(m.Root, 1, depth, flags)

        self.assertNotEqual(None, m.Root.LeftChild)
        self.assertNotEqual(None, m.Root.RightChild)
    def test_trim_tree(self):
        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hash3 = UInt256(data=binascii.unhexlify(b'cc' * 32))
        hashes = [hash1, hash2, hash3]
        m = MerkleTree(hashes)

        flags = bytearray.fromhex('0000')
        m.Trim(flags)

        self.assertEqual(None, m.Root.LeftChild)
        self.assertEqual(None, m.Root.RightChild)
    def test_node_methods(self):
        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hashes = [hash1, hash2]
        m = MerkleTree(hashes)

        self.assertEqual(True, m.Root.IsRoot())
        self.assertEqual(False, m.Root.IsLeaf())
        self.assertEqual(False, m.Root.LeftChild.IsRoot())
        self.assertEqual(True, m.Root.LeftChild.IsLeaf())

        # I have no acceptable test vector
        m.Root.LeftChild.Size()
Example #5
0
    def LoadCoins(self):
        coins = {}

        try:
            for coin in Coin.select():
                reference = CoinReference(prev_hash=UInt256(coin.TxId), prev_index=coin.Index)
                output = TransactionOutput(UInt256(coin.AssetId), Fixed8(coin.Value), UInt160(coin.ScriptHash))
                walletcoin = WalletCoin.CoinFromRef(reference, output, coin.State)
                coins[reference] = walletcoin
        except Exception as e:
            logger.error("could not load coins %s " % e)

        return coins
Example #6
0
    def test_to_hash_array(self):
        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hash3 = UInt256(data=binascii.unhexlify(b'cc' * 32))
        hash4 = UInt256(data=binascii.unhexlify(b'dd' * 32))
        hash5 = UInt256(data=binascii.unhexlify(b'ee' * 32))
        hashes = [hash1, hash2, hash3, hash4, hash5]

        m = MerkleTree(hashes)
        hash_array = m.ToHashArray()

        for i, h in enumerate(hashes):
            self.assertEqual(h.ToBytes(), hash_array[i].ToBytes())
    def test_trim_node1(self):
        hash1 = UInt256(data=binascii.unhexlify(b'aa' * 32))
        hash2 = UInt256(data=binascii.unhexlify(b'bb' * 32))
        hash3 = UInt256(data=binascii.unhexlify(b'cc' * 32))
        hashes = [hash1, hash2, hash3]
        m = MerkleTree(hashes)

        depth = 2
        flags = bytearray.fromhex(
            '11110000'
        )  # 1 byte left node , 1 byte right node  00=delete, non-00 is keep
        m._TrimNode(m.Root, 1, depth, flags)
        self.assertEqual(None, m.Root.LeftChild)
        self.assertEqual(None, m.Root.RightChild)
Example #8
0
    def test_parse(self):
        string = '0xcedb5c4e24b1f6fc5b239f2d1049c3229ad5ed05293c696b3740dc236c3f41b4'
        uint256 = UInt256.ParseString(string)
        self.assertIsInstance(uint256, UInt256)
        self.assertEqual(uint256.To0xString(), string)

        string = '9410bd44beb7d6febc9278b028158af2781fcfb40cf2c6067b3525d24eff19f6'
        uint256 = UInt256.ParseString(string)
        self.assertIsInstance(uint256, UInt256)
        self.assertEqual(uint256.ToString(), string)

        string = '9410bd44beb7d6febc9278b028158af2781fcfb40cf2c6067b3525d24eff19f'
        with self.assertRaises(Exception) as context:
            uint256 = UInt256.ParseString(string)
Example #9
0
    def GenesisBlock():
        """
        Create the GenesisBlock.

        Returns:
            BLock:
        """
        prev_hash = UInt256(data=bytearray(32))
        timestamp = int(
            datetime(2016, 7, 15, 15, 8, 21, tzinfo=pytz.utc).timestamp())
        index = 0
        consensus_data = 2083236893  # 向比特币致敬 ( Pay Tribute To Bitcoin )
        next_consensus = Blockchain.GetConsensusAddress(
            Blockchain.StandbyValidators())
        script = Witness(bytearray(0), bytearray(PUSHT))

        mt = MinerTransaction()
        mt.Nonce = 2083236893

        output = TransactionOutput(
            Blockchain.SystemShare().Hash,
            Blockchain.SystemShare().Amount,
            Crypto.ToScriptHash(
                Contract.CreateMultiSigRedeemScript(
                    int(len(Blockchain.StandbyValidators()) / 2) + 1,
                    Blockchain.StandbyValidators())))

        it = IssueTransaction([], [output], [], [script])

        return Block(
            prev_hash, timestamp, index, consensus_data, next_consensus,
            script,
            [mt, Blockchain.SystemShare(),
             Blockchain.SystemCoin(), it], True)
Example #10
0
def _createOutput(assetId, amount, address):
    assetId = UInt256(data=binascii.unhexlify(hex_reverse(assetId)))
    f8amount = Fixed8.TryParse(amount, require_positive=True)
    address_hash = ToAddresstHash(address)
    return TransactionOutput(AssetId=assetId,
                             Value=f8amount,
                             script_hash=address_hash)
Example #11
0
    def Blockchain_GetHeader(self, engine):
        data = engine.EvaluationStack.Pop().GetByteArray()

        header = None

        if len(data) <= 5:

            height = BigInteger.FromBytes(data)

            if Blockchain.Default() is not None:

                header = Blockchain.Default().GetHeaderBy(
                    height_or_hash=height)

            elif height == 0:

                header = Blockchain.GenesisBlock().Header

        elif len(data) == 32:

            hash = UInt256(data=data)

            if Blockchain.Default() is not None:

                header = Blockchain.Default().GetHeaderBy(height_or_hash=hash)

            elif hash == Blockchain.GenesisBlock().Hash:

                header = Blockchain.GenesisBlock().Header

        engine.EvaluationStack.PushT(StackItem.FromInterface(header))
        return True
Example #12
0
    def execute(self, arguments):
        item = get_arg(arguments)
        if item is not None:
            if item.lower() == "all":
                assets = Blockchain.Default().ShowAllAssets()
                assetlist = []
                for asset in assets:
                    state = Blockchain.Default().GetAssetState(asset.decode('utf-8')).ToJson()
                    asset_dict = {state['name']: state['assetId']}
                    assetlist.append(asset_dict)
                print(json.dumps(assetlist, indent=4))
                return assetlist

            if item.lower() == 'neo':
                assetId = Blockchain.Default().SystemShare().Hash
            elif item.lower() == 'gas':
                assetId = Blockchain.Default().SystemCoin().Hash
            else:
                try:
                    assetId = UInt256.ParseString(item)
                except Exception:
                    print("Could not find asset from args: %s" % arguments)
                    return

            asset = Blockchain.Default().GetAssetState(assetId.ToBytes())

            if asset is not None:
                print(json.dumps(asset.ToJson(), indent=4))
                return asset.ToJson()
            else:
                print("Asset %s not found" % item)
                return
        else:
            print('Please specify the required parameter')
            return
Example #13
0
    def __Build(leaves):
        """
        Build the merkle tree.

        Args:
            leaves (list): items are of type MerkleTreeNode.

        Returns:
            MerkleTreeNode: the root node.
        """
        if len(leaves) < 1:
            raise Exception('Leaves must have length')
        if len(leaves) == 1:
            return leaves[0]

        num_parents = int((len(leaves) + 1) / 2)
        parents = [MerkleTreeNode() for i in range(0, num_parents)]

        for i in range(0, num_parents):
            node = parents[i]
            node.LeftChild = leaves[i * 2]
            leaves[i * 2].Parent = node
            if (i * 2 + 1 == len(leaves)):
                node.RightChild = node.LeftChild
            else:
                node.RightChild = leaves[i * 2 + 1]
                leaves[i * 2 + 1].Parent = node

            hasharray = bytearray(node.LeftChild.Hash.ToArray() +
                                  node.RightChild.Hash.ToArray())
            node.Hash = UInt256(data=Crypto.Hash256(hasharray))

        return MerkleTree.__Build(parents)
Example #14
0
    def ReadUInt256(self):
        """
        Read a UInt256 value from the stream.

        Returns:
            UInt256:
        """
        return UInt256(data=bytearray(self.ReadBytes(32)))
Example #15
0
    def StaticAssetState(assetId):
        neo = AssetState()
        neo.AssetId = UInt256.ParseString("0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b")
        neo.AssetType = 0x00

        gas = AssetState()
        gas.AssetId = UInt256.ParseString("0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7")
        gas.AssetType = 0x01

        if assetId == neo.AssetId:
            return neo

        elif assetId == gas.AssetId:
            return gas

        else:
            return None
Example #16
0
    def Size(self):
        """
        Get the total size in bytes of the object.

        Returns:
            int: size.
        """
        corrected_hashes = list(map(lambda i: UInt256(data=binascii.unhexlify(i)), self.HashStart))
        return GetVarSize(corrected_hashes) + self.hash_stop.Size
Example #17
0
    def Blockchain_GetAsset(self, engine):
        data = engine.EvaluationStack.Pop().GetByteArray()
        asset = None

        if Blockchain.Default() is not None:
            asset = Blockchain.Default().GetAssetState(UInt256(data=data))

        engine.EvaluationStack.PushT(StackItem.FromInterface(asset))
        return True
Example #18
0
    def Blockchain_GetTransactionHeight(self, engine: ExecutionEngine):
        data = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()
        height = -1

        if Blockchain.Default() is not None:
            tx, height = Blockchain.Default().GetTransaction(
                UInt256(data=data))

        engine.CurrentContext.EvaluationStack.PushT(height)
        return True
    def __init__(self, hash_start=[], hash_stop=UInt256()):
        """
        Create an instance.

        Args:
            hash_start (list): a list of hash values. Each value is of the bytearray type. Note: should actually be UInt256 objects.
            hash_stop (UInt256):
        """
        self.HashStart = hash_start
        self.HashStop = hash_stop
Example #20
0
    def Blockchain_GetTransaction(self, engine):

        data = engine.EvaluationStack.Pop().GetByteArray()
        tx = None

        if Blockchain.Default() is not None:
            tx, height = Blockchain.Default().GetTransaction(UInt256(data=data))

        engine.EvaluationStack.PushT(StackItem.FromInterface(tx))
        return True
Example #21
0
    def Blockchain_GetAsset(self, engine):

        hash = UInt256(data=engine.EvaluationStack.Pop().GetByteArray())

        asset = self._assets.TryGet(hash.ToBytes())
        if asset:
            engine.EvaluationStack.PushT(StackItem.FromInterface(asset))
        else:
            engine.EvaluationStack.PushT(False)
        return True
Example #22
0
    def Account_GetBalance(self, engine):

        account = engine.EvaluationStack.Pop().GetInterface()
        assetId = UInt256(data=engine.EvaluationStack.Pop().GetByteArray())

        if account is None:
            return False
        balance = account.BalanceFor(assetId)
        engine.EvaluationStack.PushT(balance.GetData())
        return True
Example #23
0
    def ExecutionCompleted(self, engine, success, error=None):

        height = Blockchain.Default().Height + 1
        tx_hash = None

        if engine.ScriptContainer:
            tx_hash = engine.ScriptContainer.Hash

        if not tx_hash:
            tx_hash = UInt256(data=bytearray(32))

        entry_script = None
        try:
            # get the first script that was executed
            # this is usually the script that sets up the script to be executed
            entry_script = UInt160(data=engine.ExecutedScriptHashes[0])

            # ExecutedScriptHashes[1] will usually be the first contract executed
            if len(engine.ExecutedScriptHashes) > 1:
                entry_script = UInt160(data=engine.ExecutedScriptHashes[1])
        except Exception as e:
            logger.error("Could not get entry script: %s " % e)

        payload = ContractParameter(ContractParameterType.Array, value=[])
        for item in engine.EvaluationStack.Items:
            payload.Value.append(ContractParameter.ToParameter(item))

        if success:

            # dispatch all notify events, along with the success of the contract execution
            for notify_event_args in self.notifications:
                self.events_to_dispatch.append(NotifyEvent(SmartContractEvent.RUNTIME_NOTIFY, notify_event_args.State,
                                                           notify_event_args.ScriptHash, height, tx_hash,
                                                           success, engine.testMode))

            if engine.Trigger == Application:
                self.events_to_dispatch.append(SmartContractEvent(SmartContractEvent.EXECUTION_SUCCESS, payload, entry_script,
                                                                  height, tx_hash, success, engine.testMode))
            else:
                self.events_to_dispatch.append(SmartContractEvent(SmartContractEvent.VERIFICATION_SUCCESS, payload, entry_script,
                                                                  height, tx_hash, success, engine.testMode))

        else:
            payload.Value.append(ContractParameter(ContractParameterType.String, error))
            payload.Value.append(ContractParameter(ContractParameterType.String, engine._VMState))
            if engine.Trigger == Application:
                self.events_to_dispatch.append(
                    SmartContractEvent(SmartContractEvent.EXECUTION_FAIL, payload,
                                       entry_script, height, tx_hash, success, engine.testMode))
            else:
                self.events_to_dispatch.append(
                    SmartContractEvent(SmartContractEvent.VERIFICATION_FAIL, payload,
                                       entry_script, height, tx_hash, success, engine.testMode))

        self.notifications = []
Example #24
0
    def Blockchain_GetAsset(self, engine: ExecutionEngine):
        data = engine.CurrentContext.EvaluationStack.Pop().GetByteArray()
        asset = None

        if Blockchain.Default() is not None:
            asset = self.Assets.TryGet(UInt256(data=data))
        if asset is None:
            return False
        engine.CurrentContext.EvaluationStack.PushT(
            StackItem.FromInterface(asset))
        return True
Example #25
0
    def Size(self):
        """
        Get the total size in bytes of the object.

        Returns:
            int: size.
        """
        if len(self.Hashes) > 0:
            if not isinstance(self.Hashes[0], UInt256):
                corrected_hashes = list(map(lambda i: UInt256(data=binascii.unhexlify(i)), self.Hashes))
        return s.uint8 + GetVarSize(corrected_hashes)
    def Hash(self):
        """
        Get the hash of the transaction.

        Returns:
            UInt256:
        """
        if not self.__hash:
            ba = bytearray(binascii.unhexlify(self.GetHashData()))
            hash = Crypto.Hash256(ba)
            self.__hash = UInt256(data=hash)
        return self.__hash
Example #27
0
def create_tx(contract_hash, address_from, address_to, tnc_amount, gas_change,
              input_txid, preIndex):

    nep5TokenId = get_nep5token_id(contract_hash)
    scripthash_from = ToScriptHash(address_from)
    scripthash_to = ToScriptHash(address_to)
    f8amount = amount_from_string(nep5TokenId, tnc_amount)
    f8amount_change = Fixed8.TryParse(gas_change, require_positive=True)
    assetId = get_asset_id("gas")
    preHash = UInt256(data=binascii.unhexlify(hex_reverse(input_txid)))

    input = TransactionInput(prevHash=preHash, prevIndex=preIndex)
    output = TransactionOutput(AssetId=assetId,
                               Value=f8amount_change,
                               script_hash=scripthash_from)

    tx = InvocationTransaction(outputs=[output], inputs=[input])
    tx.Version = 1
    context = ContractParametersContext(tx)
    tx.scripts = context.GetScripts()

    invoke_args = [
        nep5TokenId.ScriptHash, 'transfer',
        [
            bytearray.fromhex(hex_reverse(scripthash_from.ToString())),
            bytearray.fromhex(hex_reverse(scripthash_to.ToString())),
            BigInteger(f8amount)
        ]
    ]
    sb = ScriptBuilder()
    invoke_args.reverse()
    for item in invoke_args[:2]:
        if type(item) is list:
            item.reverse()
            listlength = len(item)
            for listitem in item:
                sb.push(listitem)
            sb.push(listlength)
            sb.Emit(PACK)
        else:
            sb.push(binascii.hexlify(item.encode()))

    sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray())

    op_data = sb.ToArray().decode()
    tx.Script = binascii.unhexlify(op_data)
    tx_data = get_tx_data(tx)[:-2]
    print("tx_data:", tx_data)
    signstr = binascii.hexlify(
        Crypto.Sign(message=tx_data, private_key=private_key)).decode()
    rawtx_data = tx_data + "014140" + signstr + "2321" + public_key + "ac"
    return rawtx_data
Example #28
0
    def test_interop_get_bad_transaction_height(self):
        u256 = UInt256.ParseString(
            '8be9660512991d36e016b8ced6fda5d611d26a0f6e2faaaf1f379496edb33956')

        hash = StackItem.New(u256.Data)

        self.econtext.EvaluationStack.PushT(hash)
        self.engine.InvocationStack.PushT(self.econtext)
        self.state_reader.Blockchain_GetTransactionHeight(self.engine)

        height = self.econtext.EvaluationStack.Pop().GetBigInteger()

        self.assertEqual(height, -1)
Example #29
0
    def test_interop_get_bad_transaction(self):

        u256 = UInt256.ParseString(
            'e4d2ea5df2adf77df91049beccbb16f98863b93a16439c60381eac1f23bff176')

        hash = StackItem.New(u256.Data)

        self.engine.EvaluationStack.PushT(hash)
        self.state_reader.Blockchain_GetTransaction(self.engine)

        tx = self.engine.EvaluationStack.Pop().GetInterface()

        self.assertIsNone(tx)
Example #30
0
    def test_interop_get_bad_transaction_height(self):

        u256 = UInt256.ParseString(
            'e4d2ea5df2adf77df91049beccbb16f98863b93a16439c60381eac1f23bff176')

        hash = StackItem.New(u256.Data)

        self.engine.EvaluationStack.PushT(hash)
        self.state_reader.Blockchain_GetTransactionHeight(self.engine)

        height = self.engine.EvaluationStack.Pop().GetBigInteger()

        self.assertEqual(height, -1)