Beispiel #1
0
 public static TrimmedBlock GetTrimmedBlockWithNoTransaction()
 {
     return(new TrimmedBlock
     {
         ConsensusData = new ConsensusData(),
         MerkleRoot = UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff02"),
         PrevHash = UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff01"),
         Timestamp = new DateTime(1988, 06, 01, 0, 0, 0, DateTimeKind.Utc).ToTimestamp(),
         Index = 1,
         NextConsensus = UInt160.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff01"),
         Witness = new Witness
         {
             InvocationScript = Array.Empty <byte>(),
             VerificationScript = new[] { (byte)OpCode.PUSH1 }
         },
         Hashes = Array.Empty <UInt256>()
     });
 }
Beispiel #2
0
        public static Block GetBlockFromJson(string blockJson)
        {
            var block = Json.Decode(blockJson);

            return(new Block
                   (
                       header: new BlockHeader
                       (
                           version: Convert.ToUInt32(block.ver),
                           previousBlock: UInt256.Parse(block.prev_block, NumberStyles.HexNumber),
                           merkleRoot: UInt256.Parse(block.mrkl_root, NumberStyles.HexNumber),
                           time: Convert.ToUInt32(block.time),
                           bits: Convert.ToUInt32(block.bits),
                           nonce: Convert.ToUInt32(block.nonce)
                       ),
                       transactions: ReadTransactions(block.tx)
                   ));
        }
Beispiel #3
0
 private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal)
 {
     bb.PrevHash      = val256;
     merkRootVal      = UInt256.Parse("0xd841af3d6bd7adb4bca24306725f9aec363edb10de3cafc5f8cca948d7b0290f");
     bb.MerkleRoot    = merkRootVal;
     timestampVal     = new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc).ToTimestampMS(); // GMT: Sunday, June 1, 1980 12:00:01.001 AM
     bb.Timestamp     = timestampVal;
     indexVal         = 0;
     bb.Index         = indexVal;
     val160           = UInt160.Zero;
     bb.NextConsensus = val160;
     scriptVal        = new Witness
     {
         InvocationScript   = new byte[0],
         VerificationScript = new[] { (byte)OpCode.PUSHT }
     };
     bb.Witness = scriptVal;
 }
Beispiel #4
0
        public void TestStringAdd()
        {
            var result = _engine.ExecuteTestCaseStandard("isZeroUInt256", UInt256.Zero.ToArray());

            Assert.IsTrue(result.Pop().GetBoolean());

            _engine.Reset();
            result = _engine.ExecuteTestCaseStandard("isZeroUInt160", UInt160.Zero.ToArray());
            Assert.IsTrue(result.Pop().GetBoolean());

            _engine.Reset();
            result = _engine.ExecuteTestCaseStandard("isZeroUInt256", UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff01").ToArray());
            Assert.IsFalse(result.Pop().GetBoolean());

            _engine.Reset();
            result = _engine.ExecuteTestCaseStandard("isZeroUInt160", UInt160.Parse("01ff00ff00ff00ff00ff00ff00ff00ff00ff00a4").ToArray());
            Assert.IsFalse(result.Pop().GetBoolean());
        }
Beispiel #5
0
        public override Account ReadJson(JsonReader reader, Type objectType, Account existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            Debug.Assert(reader.TokenType == JsonToken.StartObject);

            // TODO: read w/o loading full JObject
            var result = JObject.ReadFrom(reader);

            var scriptHash = result.Value <string>("script_hash").ToScriptHash();
            var isFrozen   = result.Value <bool>("frozen");
            var votes      = result["votes"]
                             .Select(t => EncodedPublicKey.Parse(t.Value <string>()))
                             .ToImmutableArray();
            var balances = result["balances"].ToImmutableDictionary(
                t => UInt256.Parse(t.Value <string>("asset")),
                t => Fixed8.Parse(t.Value <string>("value")));

            return(new Account(scriptHash, isFrozen, votes, balances));
        }
Beispiel #6
0
 private static void setupBlockBaseWithValues(BlockBase bb, UInt256 val256, out UInt256 merkRootVal, out UInt160 val160, out ulong timestampVal, out uint indexVal, out Witness scriptVal)
 {
     bb.PrevHash      = val256;
     merkRootVal      = UInt256.Parse("0x6226416a0e5aca42b5566f5a19ab467692688ba9d47986f6981a7f747bba2772");
     bb.MerkleRoot    = merkRootVal;
     timestampVal     = new DateTime(1980, 06, 01, 0, 0, 1, 001, DateTimeKind.Utc).ToTimestampMS(); // GMT: Sunday, June 1, 1980 12:00:01.001 AM
     bb.Timestamp     = timestampVal;
     indexVal         = 0;
     bb.Index         = indexVal;
     val160           = UInt160.Zero;
     bb.NextConsensus = val160;
     scriptVal        = new Witness
     {
         InvocationScript   = new byte[0],
         VerificationScript = new[] { (byte)OpCode.PUSH1 }
     };
     bb.Witness = scriptVal;
 }
Beispiel #7
0
        public void TestCreateDummyBlock()
        {
            var          mockSnapshot     = new Mock <Snapshot>();
            UInt256      currentBlockHash = UInt256.Parse("0x0000000000000000000000000000000000000000000000000000000000000000");
            TrimmedBlock block            = new TrimmedBlock();
            var          cache            = new TestDataCache <UInt256, TrimmedBlock>();

            cache.Add(currentBlockHash, block);
            mockSnapshot.SetupGet(p => p.Blocks).Returns(cache);
            TestMetaDataCache <HashIndexState> testCache = new TestMetaDataCache <HashIndexState>();

            mockSnapshot.SetupGet(p => p.BlockHashIndex).Returns(testCache);
            byte[] SyscallSystemRuntimeCheckWitnessHash = new byte[] { 0x68, 0xf8, 0x27, 0xec, 0x8c };
            ApplicationEngine.Run(SyscallSystemRuntimeCheckWitnessHash, mockSnapshot.Object);
            mockSnapshot.Object.PersistingBlock.Version.Should().Be(0);
            mockSnapshot.Object.PersistingBlock.PrevHash.Should().Be(currentBlockHash);
            mockSnapshot.Object.PersistingBlock.MerkleRoot.Should().Be(new UInt256());
        }
Beispiel #8
0
        public static void InitTransactionContext(string scriptHash, int value, ushort inputAmount = 1)
        {
            Transaction initialTransaction = new CustomTransaction(TransactionType.ContractTransaction);
            Transaction currentTransaction = new CustomTransaction(TransactionType.ContractTransaction);

            initialTransaction.Outputs = new TransactionOutput[inputAmount];
            currentTransaction.Inputs  = new CoinReference[inputAmount];


            for (ushort i = 0; i < inputAmount; ++i)
            {
                /** CREATE FAKE PREVIOUS TRANSACTION */
                var transactionOutput = new TransactionOutput
                {
                    ScriptHash = UInt160.Parse(scriptHash),
                    Value      = new Fixed8(value),
                    AssetId    = UInt256.Parse(NEO_ASSET_ID)
                };

                initialTransaction.Outputs[i] = transactionOutput;
                /** CREATE FAKE CURRENT TRANSACTION */
                var coinRef = new CoinReference
                {
                    PrevHash  = initialTransaction.Hash,
                    PrevIndex = i
                };

                currentTransaction.Outputs    = new TransactionOutput[1];
                currentTransaction.Outputs[0] = new TransactionOutput
                {
                    ScriptHash = UInt160.Parse(scriptHash),
                    Value      = new Fixed8(value),
                    AssetId    = UInt256.Parse(NEO_ASSET_ID)
                };


                currentTransaction.Inputs[i] = coinRef;
            }


            /**INIT CONTEXT*/
            service.transactions[initialTransaction.Hash] = initialTransaction;
            scriptContainer = currentTransaction;
        }
Beispiel #9
0
        private bool OnShowUtxoCommand(string[] args)
        {
            if (Program.Wallet == null)
            {
                Console.WriteLine("You have to open the wallet first.");
                return(true);
            }
            IEnumerable <Coin> coins = Program.Wallet.FindUnspentCoins();

            if (args.Length >= 3)
            {
                UInt256 assetId;
                switch (args[2].ToLower())
                {
                case "pure":
                case "ans":
                    assetId = Blockchain.GoverningToken.Hash;
                    break;

                case "gas":
                case "anc":
                    assetId = Blockchain.UtilityToken.Hash;
                    break;

                default:
                    assetId = UInt256.Parse(args[2]);
                    break;
                }
                coins = coins.Where(p => p.Output.AssetId.Equals(assetId));
            }
            Coin[]    coins_array = coins.ToArray();
            const int MAX_SHOW    = 100;

            for (int i = 0; i < coins_array.Length && i < MAX_SHOW; i++)
            {
                Console.WriteLine($"{coins_array[i].Reference.PrevHash}:{coins_array[i].Reference.PrevIndex}");
            }
            if (coins_array.Length > MAX_SHOW)
            {
                Console.WriteLine($"({coins_array.Length - MAX_SHOW} more)");
            }
            Console.WriteLine($"total: {coins_array.Length} UTXOs");
            return(true);
        }
Beispiel #10
0
        private Transaction MakeTran()
        {
            Transaction tx = new ContractTransaction();
            List <TransactionAttribute> attributes = new List <TransactionAttribute>();

            tx.Attributes = attributes.ToArray();


            TransactionOutput[] outputs = new TransactionOutput[1];
            outputs[0]         = new TransactionOutput();
            outputs[0].AssetId = UInt256.Parse(dAsset[comAsset.Text]);

            outputs[0].Value = new BigDecimal(Fixed8.Parse(amountText.Text).GetData(), 8).ToFixed8();

            outputs[0].ScriptHash = Wallet.ToScriptHash(targetAddr.Text.ToString());
            tx.Outputs            = outputs;
            tx = plugin_multisign.api.CurrentWallet.MakeTransaction(tx, change_address: plugin_multisign.api.CurrentWallet.GetChangeAddress(), fee: Fixed8.Zero);
            return(tx);
        }
        private static object GetValue(Type valueType, string itemValue)
        {
            if (valueType == typeof(UInt256))
            {
                return(UInt256.Parse(itemValue));
            }

            if (valueType.IsEnum)
            {
                if (Enum.TryParse(valueType, itemValue, true, out var enumValue))
                {
                    return(enumValue);
                }

                throw new IOException($"Cannot parse enum value: {itemValue}, type: {valueType.Name}");
            }

            return(Convert.ChangeType(itemValue, valueType));
        }
        public void Can_load_sokol()
        {
            string    path      = Path.Combine(TestContext.CurrentContext.WorkDirectory, "../../../../", "Chains/sokol.json");
            ChainSpec chainSpec = LoadChainSpec(path);

            Assert.AreEqual(1.GWei(), chainSpec.Parameters.Eip1559BaseFeeInitialValue, $"fork base fee");
            Assert.AreEqual(0x4d, chainSpec.ChainId, $"{nameof(chainSpec.ChainId)}");
            Assert.AreEqual("Sokol", chainSpec.Name, $"{nameof(chainSpec.Name)}");
            Assert.AreEqual(SealEngineType.AuRa, chainSpec.SealEngineType, "engine");
            Assert.NotNull(chainSpec.AuRa, "AuRa");
            Assert.AreEqual(0, chainSpec.AuRa.MaximumUncleCount, "maximum uncle count");
            Assert.AreEqual(0L, chainSpec.AuRa.MaximumUncleCountTransition, "maximum uncle count tr");
            Assert.AreEqual(5L, chainSpec.AuRa.StepDuration[0], "step duration");
            Assert.AreEqual(UInt256.Parse("1000000000000000000"), chainSpec.AuRa.BlockReward[0], "rew");
            Assert.AreEqual(4639000, chainSpec.AuRa.BlockRewardContractTransition, "rew tr");
            Assert.AreEqual(new Address("0x3145197AD50D7083D0222DE4fCCf67d9BD05C30D"), chainSpec.AuRa.BlockRewardContractAddress, "rew add");

            Assert.AreEqual(new Address("0x8bf38d4764929064f2d4d3a56520a76ab3df415b"), chainSpec.AuRa.Validators.Validators[0].Addresses.First(), "val 0");
            Assert.AreEqual(new Address("0xf5cE3f5D0366D6ec551C74CCb1F67e91c56F2e34"), chainSpec.AuRa.Validators.Validators[362296].Addresses.First(), "val 362296");
            Assert.AreEqual(new Address("0x03048F666359CFD3C74a1A5b9a97848BF71d5038"), chainSpec.AuRa.Validators.Validators[509355].Addresses.First(), "val 509355");
            Assert.AreEqual(new Address("0x4c6a159659CCcb033F4b2e2Be0C16ACC62b89DDB"), chainSpec.AuRa.Validators.Validators[4622420].Addresses.First(), "val 4622420");

            Assert.AreEqual(0, chainSpec.HomesteadBlockNumber, "homestead no");
            Assert.AreEqual(null, chainSpec.DaoForkBlockNumber, "dao no");

            Assert.AreEqual((long?)0, chainSpec.Parameters.Eip140Transition, "eip140");

            Assert.AreEqual((long?)0, chainSpec.Parameters.Eip150Transition, "eip150");
            Assert.AreEqual((long?)0, chainSpec.Parameters.Eip160Transition, "eip160");
            Assert.AreEqual((long?)0, chainSpec.Parameters.Eip161abcTransition, "eip161abc");
            Assert.AreEqual((long?)0, chainSpec.Parameters.Eip161dTransition, "eip161d");

            Assert.AreEqual((long?)0, chainSpec.TangerineWhistleBlockNumber, "tw no");
            Assert.AreEqual((long?)0, chainSpec.SpuriousDragonBlockNumber, "sd no");

            Assert.AreEqual((long?)0, chainSpec.ByzantiumBlockNumber, "byzantium no");
            Assert.AreEqual((long?)6464300, chainSpec.ConstantinopleBlockNumber, "constantinople no");
            Assert.AreEqual((long?)7026400, chainSpec.ConstantinopleFixBlockNumber, "constantinople fix no");
            Assert.AreEqual((long?)12095200, chainSpec.Parameters.Eip1706Transition, "eip2200");
            Assert.AreEqual((long?)12095200, chainSpec.Parameters.Eip1283ReenableTransition, "eip2200");

            Assert.AreEqual("0x606060405260008060006101000a81548160ff0219169083151502179055506000600460006101000a81548160ff0219169083151502179055506000600460016101000a81548160ff02191690831515021790555073fffffffffffffffffffffffffffffffffffffffe600560006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055503415620000b557600080fd5b604051602080620018c98339810160405280805190602001909190505060008073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141515156200011057600080fd5b81600460026101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550602060405190810160405280600460029054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152506006906001620001c1929190620002cb565b50600090505b600680549050811015620002a257604080519081016040528060011515815260200182815250600960006006848154811015156200020157fe5b906000526020600020900160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008201518160000160006101000a81548160ff021916908315150217905550602082015181600101559050508080600101915050620001c7565b60068054905060088190555060066007908054620002c29291906200035a565b505050620003f7565b82805482825590600052602060002090810192821562000347579160200282015b82811115620003465782518260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555091602001919060010190620002ec565b5b509050620003569190620003b1565b5090565b8280548282559060005260206000209081019282156200039e5760005260206000209182015b828111156200039d57825482559160010191906001019062000380565b5b509050620003ad9190620003b1565b5090565b620003f491905b80821115620003f057600081816101000a81549073ffffffffffffffffffffffffffffffffffffffff021916905550600101620003b8565b5090565b90565b6114c280620004076000396000f3006060604052600436106100fc576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806303aca79214610101578063108552691461016457806340a141ff1461019d57806340c9cdeb146101d65780634110a489146101ff57806345199e0a1461025757806349285b58146102c15780634d238c8e14610316578063752862111461034f578063900eb5a8146103645780639a573786146103c7578063a26a47d21461041c578063ae4b1b5b14610449578063b3f05b971461049e578063b7ab4db5146104cb578063d3e848f114610535578063fa81b2001461058a578063facd743b146105df575b600080fd5b341561010c57600080fd5b6101226004808035906020019091905050610630565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561016f57600080fd5b61019b600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061066f565b005b34156101a857600080fd5b6101d4600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610807565b005b34156101e157600080fd5b6101e9610bb7565b6040518082815260200191505060405180910390f35b341561020a57600080fd5b610236600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610bbd565b60405180831515151581526020018281526020019250505060405180910390f35b341561026257600080fd5b61026a610bee565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156102ad578082015181840152602081019050610292565b505050509050019250505060405180910390f35b34156102cc57600080fd5b6102d4610c82565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561032157600080fd5b61034d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610d32565b005b341561035a57600080fd5b610362610fcc565b005b341561036f57600080fd5b61038560048080359060200190919050506110fc565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156103d257600080fd5b6103da61113b565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561042757600080fd5b61042f6111eb565b604051808215151515815260200191505060405180910390f35b341561045457600080fd5b61045c6111fe565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156104a957600080fd5b6104b1611224565b604051808215151515815260200191505060405180910390f35b34156104d657600080fd5b6104de611237565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b83811015610521578082015181840152602081019050610506565b505050509050019250505060405180910390f35b341561054057600080fd5b6105486112cb565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b341561059557600080fd5b61059d6112f1565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156105ea57600080fd5b610616600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050611317565b604051808215151515815260200191505060405180910390f35b60078181548110151561063f57fe5b90600052602060002090016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600460029054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156106cb57600080fd5b600460019054906101000a900460ff161515156106e757600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415151561072357600080fd5b80600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506001600460016101000a81548160ff0219169083151502179055507f600bcf04a13e752d1e3670a5a9f1c21177ca2a93c6f5391d4f1298d098097c22600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390a150565b600080600061081461113b565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561084d57600080fd5b83600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000160009054906101000a900460ff1615156108a957600080fd5b600960008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101549350600160078054905003925060078381548110151561090857fe5b906000526020600020900160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1691508160078581548110151561094657fe5b906000526020600020900160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555083600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101819055506007838154811015156109e557fe5b906000526020600020900160006101000a81549073ffffffffffffffffffffffffffffffffffffffff02191690556000600780549050111515610a2757600080fd5b6007805480919060019003610a3c9190611370565b506000600960008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101819055506000600960008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000160006101000a81548160ff0219169083151502179055506000600460006101000a81548160ff0219169083151502179055506001430340600019167f55252fa6eee4741b4e24a74a70e9c11fd2c2281df8d6ea13126ff845f7825c89600760405180806020018281038252838181548152602001915080548015610ba257602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311610b58575b50509250505060405180910390a25050505050565b60085481565b60096020528060005260406000206000915090508060000160009054906101000a900460ff16908060010154905082565b610bf661139c565b6007805480602002602001604051908101604052809291908181526020018280548015610c7857602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311610c2e575b5050505050905090565b6000600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166349285b586000604051602001526040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b1515610d1257600080fd5b6102c65a03f11515610d2357600080fd5b50505060405180519050905090565b610d3a61113b565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610d7357600080fd5b80600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000160009054906101000a900460ff16151515610dd057600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614151515610e0c57600080fd5b6040805190810160405280600115158152602001600780549050815250600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008201518160000160006101000a81548160ff0219169083151502179055506020820151816001015590505060078054806001018281610ea991906113b0565b9160005260206000209001600084909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550506000600460006101000a81548160ff0219169083151502179055506001430340600019167f55252fa6eee4741b4e24a74a70e9c11fd2c2281df8d6ea13126ff845f7825c89600760405180806020018281038252838181548152602001915080548015610fba57602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311610f70575b50509250505060405180910390a25050565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161480156110365750600460009054906101000a900460ff16155b151561104157600080fd5b6001600460006101000a81548160ff0219169083151502179055506007600690805461106e9291906113dc565b506006805490506008819055507f8564cd629b15f47dc310d45bcbfc9bcf5420b0d51bf0659a16c67f91d27632536110a4611237565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156110e75780820151818401526020810190506110cc565b505050509050019250505060405180910390a1565b60068181548110151561110b57fe5b90600052602060002090016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639a5737866000604051602001526040518163ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401602060405180830381600087803b15156111cb57600080fd5b6102c65a03f115156111dc57600080fd5b50505060405180519050905090565b600460019054906101000a900460ff1681565b600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600460009054906101000a900460ff1681565b61123f61139c565b60068054806020026020016040519081016040528092919081815260200182805480156112c157602002820191906000526020600020905b8160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019060010190808311611277575b5050505050905090565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600460029054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000160009054906101000a900460ff169050919050565b81548183558181151161139757818360005260206000209182019101611396919061142e565b5b505050565b602060405190810160405280600081525090565b8154818355818115116113d7578183600052602060002091820191016113d6919061142e565b5b505050565b82805482825590600052602060002090810192821561141d5760005260206000209182015b8281111561141c578254825591600101919060010190611401565b5b50905061142a9190611453565b5090565b61145091905b8082111561144c576000816000905550600101611434565b5090565b90565b61149391905b8082111561148f57600081816101000a81549073ffffffffffffffffffffffffffffffffffffffff021916905550600101611459565b5090565b905600a165627a7a7230582036ea35935c8246b68074adece2eab70c40e69a0193c08a6277ce06e5b25188510029000000000000000000000000e8ddc5c7a2d2f0d7a9798459c0104fdf5e987aca", chainSpec.Allocations[new Address("0x8bf38d4764929064f2d4d3a56520a76ab3df415b")].Constructor?.ToHexString(true), "constantinople no");
        }
        public JObject OnGetApplicationLog(JArray @params)
        {
            var hash  = UInt256.Parse(@params[0].AsString());
            var value = store.Get(APP_LOGS_PREFIX, hash.ToArray());

            if (value != null && value.Length > 0)
            {
                var json = Encoding.UTF8.GetString(value);
                return(JObject.Parse(json));
            }

            // I'd rather be returning JObject.Null here, but Neo's RPC plugin
            // infrastructure can't distingish between null return meaning
            // "this plugin doesn't support this method" and JObject.Null return
            // meaning "this plugin does support this method, but there was a null
            // return value". So I'm using an empty string as the null response.

            return(string.Empty);
        }
Beispiel #14
0
        /// <summary>
        ///  Paged by Transactions
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public PageList <TransactionInfo> FindTransactions(TransactionFilter filter)
        {
            IQueryable <TransactionEntity> query = _sqldb.Transactions.Include(tx => tx.Sender);

            if (filter.StartTime != null)
            {
                query = query.Where(r => r.Time >= filter.StartTime.Value.ToUniversalTime());
            }
            if (filter.EndTime != null)
            {
                query = query.Where(r => r.Time <= filter.EndTime.Value.ToUniversalTime());
            }

            if (filter.BlockHeight != null)
            {
                query = query.Where(r => r.BlockHeight == filter.BlockHeight);
            }
            if (filter.TxIds.NotEmpty())
            {
                var txids = filter.TxIds.Select(t => t.ToBigEndianHex()).Distinct().ToList();
                query = query.Where(r => txids.Contains(r.TxId));
            }

            var pageList  = new PageList <TransactionInfo>();
            var pageIndex = filter.PageIndex <= 0 ? 0 : filter.PageIndex - 1;

            pageList.TotalCount = query.Count();
            pageList.PageIndex  = pageIndex + 1;
            pageList.PageSize   = filter.PageSize;
            if (filter.PageSize > 0)
            {
                pageList.List.AddRange(query.OrderByDescending(g => g.Time)
                                       .Skip(pageIndex * filter.PageSize)
                                       .Take(filter.PageSize).Select(tx => new TransactionInfo()
                {
                    TxId        = UInt256.Parse(tx.TxId),
                    BlockHeight = tx.BlockHeight,
                    Sender      = tx.Sender != null ? UInt160.Parse(tx.Sender.Address) : null,
                    Time        = tx.Time.AsUtcTime(),
                }));
            }
            return(pageList);
        }
Beispiel #15
0
        private bool OnBroadcastCommand(string[] args)
        {
            string        command = args[1].ToLower();
            ISerializable payload = null;

            switch (command)
            {
            case "addr":
                payload = AddrPayload.Create(NetworkAddressWithTime.Create(new IPEndPoint(IPAddress.Parse(args[2]), ushort.Parse(args[3])), NetworkAddressWithTime.NODE_NETWORK, DateTime.UtcNow.ToTimestamp()));
                break;

            case "block":
                if (args[2].Length == 64 || args[2].Length == 66)
                {
                    payload = Blockchain.Singleton.GetBlock(UInt256.Parse(args[2]));
                }
                else
                {
                    payload = Blockchain.Singleton.Store.GetBlock(uint.Parse(args[2]));
                }
                break;

            case "getblocks":
            case "getheaders":
                payload = GetBlocksPayload.Create(UInt256.Parse(args[2]));
                break;

            case "getdata":
            case "inv":
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[2], true), args.Skip(3).Select(UInt256.Parse).ToArray());
                break;

            case "tx":
                payload = Blockchain.Singleton.GetTransaction(UInt256.Parse(args[2]));
                break;

            default:
                Console.WriteLine($"Command \"{command}\" is not supported.");
                return(true);
            }
            system.LocalNode.Tell(Message.Create(command, payload));
            return(true);
        }
Beispiel #16
0
        public void SetValue(string text)
        {
            switch (Type)
            {
            case ContractParameterType.Signature:
                byte[] signature = text.HexToBytes();
                if (signature.Length != 64)
                {
                    throw new FormatException();
                }
                Value = signature;
                break;

            case ContractParameterType.Boolean:
                Value = string.Equals(text, bool.TrueString, StringComparison.OrdinalIgnoreCase);
                break;

            case ContractParameterType.Integer:
                Value = BigInteger.Parse(text);
                break;

            case ContractParameterType.Hash160:
                Value = UInt160.Parse(text);
                break;

            case ContractParameterType.Hash256:
                Value = UInt256.Parse(text);
                break;

            case ContractParameterType.ByteArray:
                Value = text.HexToBytes();
                break;

            case ContractParameterType.PublicKey:
                Value = ECPoint.Parse(text, ECCurve.Secp256r1);
                break;

            case ContractParameterType.String:
                Value = text;
                break;
            }
        }
Beispiel #17
0
        private static JObject InternalCall(string method, JArray _params)
        {
            switch (method)
            {
            case "getbestblockhash":
                return(Blockchain.Default.CurrentBlockHash.ToString());

            case "getblock":
            {
                UInt256 hash  = UInt256.Parse(_params[0].AsString());
                Block   block = Blockchain.Default.GetBlock(hash);
                if (block == null)
                {
                    throw new RpcException(-100, "Unknown block");
                }
                return(block.ToJson());
            }

            case "getblockcount":
                return(Blockchain.Default.Height + 1);

            case "getblockhash":
            {
                uint height = (uint)_params[0].AsNumber();
                return(Blockchain.Default.GetBlockHash(height).ToString());
            }

            case "getrawtransaction":
            {
                UInt256     hash = UInt256.Parse(_params[0].AsString());
                Transaction tx   = Blockchain.Default.GetTransaction(hash);
                if (tx == null)
                {
                    throw new RpcException(-101, "Unknown transaction");
                }
                return(tx.ToJson());
            }

            default:
                throw new RpcException(-32601, "Method not found");
            }
        }
Beispiel #18
0
        public void TestGetBlock()
        {
            var snapshot = TestBlockchain.GetTestSnapshot();
            var tx1      = TestUtils.GetTransaction(UInt160.Zero);

            tx1.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01 };
            var state1 = new TransactionState
            {
                Transaction = tx1,
                BlockIndex  = 1
            };
            var tx2 = TestUtils.GetTransaction(UInt160.Zero);

            tx2.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x02 };
            var state2 = new TransactionState
            {
                Transaction = tx2,
                BlockIndex  = 1
            };

            UT_SmartContractHelper.TransactionAdd(snapshot, state1, state2);

            TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction();

            tblock.Hashes = new UInt256[] { tx1.Hash, tx2.Hash };
            UT_SmartContractHelper.BlocksAdd(snapshot, tblock.Hash, tblock);

            Block block = NativeContract.Ledger.GetBlock(snapshot, tblock.Hash);

            block.Index.Should().Be(1);
            block.MerkleRoot.Should().Be(UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff02"));
            block.Transactions.Length.Should().Be(2);
            block.Transactions[0].Hash.Should().Be(tx1.Hash);
            block.Witness.InvocationScript.ToHexString().Should().Be(tblock.Header.Witness.InvocationScript.ToHexString());
            block.Witness.VerificationScript.ToHexString().Should().Be(tblock.Header.Witness.VerificationScript.ToHexString());
        }
Beispiel #19
0
        public static Block GetRinkebyGenesis()
        {
            Keccak  parentHash  = Keccak.Zero;
            Keccak  ommersHash  = Keccak.OfAnEmptySequenceRlp;
            Address beneficiary = Address.Zero;
            UInt256 difficulty  = new UInt256(1);
            long    number      = 0L;
            int     gasLimit    = 4700000;
            UInt256 timestamp   = UInt256.Parse("1492009146");

            byte[]      extraData = Bytes.FromHexString("52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
            BlockHeader header    = new BlockHeader(parentHash, ommersHash, beneficiary, difficulty, number, gasLimit, timestamp, extraData);
            Block       genesis   = new Block(header);

            genesis.Header.Hash = new Keccak("0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177");
            // this would need to be loaded from rinkeby chainspec to include allocations
            // Assert.AreEqual(new Keccak("0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177"), genesis.Hash);

            return(genesis);
        }
        public IActionResult GetBlock(string hash, int index, bool verbose = false)
        {
            JObject key;

            if (hash != null)
            {
                key = new JString(hash);
            }
            else
            {
                key = new JNumber(index);
            }
            Block block;

            if (key is JNumber)
            {
                uint _index = uint.Parse(key.AsString());
                block = Blockchain.Singleton.GetBlock(_index);
            }
            else
            {
                UInt256 _hash = UInt256.Parse(key.AsString());
                block = Blockchain.Singleton.View.GetBlock(_hash);
            }
            if (block == null)
            {
                throw new RestException(-100, "Unknown block");
            }
            if (verbose)
            {
                JObject json = block.ToJson();
                json["confirmations"] = Blockchain.Singleton.Height - block.Index + 1;
                UInt256 _hash = Blockchain.Singleton.GetNextBlockHash(block.Hash);
                if (hash != null)
                {
                    json["nextblockhash"] = hash.ToString();
                }
                return(FormatJson(json));
            }
            return(FormatJson(block.ToArray().ToHexString()));
        }
Beispiel #21
0
        public void Can_load_a_private_network_file()
        {
            byte[]            data      = File.ReadAllBytes(Path.Combine(TestContext.CurrentContext.WorkDirectory, "Specs/genesis_test.json"));
            GenesisFileLoader loader    = new GenesisFileLoader(new EthereumJsonSerializer());
            ChainSpec         chainSpec = loader.Load(data);

            Assert.AreEqual(22082, chainSpec.ChainId, $"{nameof(chainSpec.ChainId)}");
            Assert.AreEqual(null, chainSpec.Name, $"{nameof(chainSpec.Name)}");
            Assert.NotNull(chainSpec.Genesis, $"{nameof(Core.Specs.ChainSpecStyle.ChainSpec.Genesis)}");

            Assert.AreEqual(0x0000000000000000UL, chainSpec.Genesis.Header.Nonce, $"genesis {nameof(BlockHeader.Nonce)}");
            Assert.AreEqual(Keccak.Zero, chainSpec.Genesis.Header.MixHash, $"genesis {nameof(BlockHeader.MixHash)}");
            Assert.AreEqual(1L, (long)chainSpec.Genesis.Header.Difficulty, $"genesis {nameof(BlockHeader.Difficulty)}");
            Assert.AreEqual(Address.Zero, chainSpec.Genesis.Header.Beneficiary, $"genesis {nameof(BlockHeader.Beneficiary)}");
            Assert.AreEqual(0x5c28d2a1L, (long)chainSpec.Genesis.Header.Timestamp, $"genesis {nameof(BlockHeader.Timestamp)}");
            Assert.AreEqual(Keccak.Zero, chainSpec.Genesis.Header.ParentHash, $"genesis {nameof(BlockHeader.ParentHash)}");
            Assert.AreEqual(
                Bytes.FromHexString("0x000000000000000000000000000000000000000000000000000000000000000020b2e4bb8688a44729780d15dc64adb42f9f5a0a746526c3a59db995b914a319306cd7ae35dc50c5aa42104423e00a862b616f2f712a1b17d308bbc90000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"),
                chainSpec.Genesis.Header.ExtraData,
                $"genesis {nameof(BlockHeader.ExtraData)}");
            Assert.AreEqual(4700000L, chainSpec.Genesis.Header.GasLimit, $"genesis {nameof(BlockHeader.GasLimit)}");

            Assert.NotNull(chainSpec.Allocations, $"{nameof(Core.Specs.ChainSpecStyle.ChainSpec.Allocations)}");
            Assert.AreEqual(16, chainSpec.Allocations.Count, $"allocations count");
            Assert.AreEqual(
                (UInt256.Parse("200000000000000000000000000000000000000000000000000000000000000", NumberStyles.HexNumber), (byte[])null),
                chainSpec.Allocations[new Address("20b2e4bb8688a44729780d15dc64adb42f9f5a0a")],
                "account 20b2e4bb8688a44729780d15dc64adb42f9f5a0a");

            Assert.AreEqual(SealEngineType.Clique, chainSpec.SealEngineType, "engine");
            Assert.AreEqual(15UL, chainSpec.Clique.Period, "Clique.period");
            Assert.AreEqual(30000UL, chainSpec.Clique.Epoch, "Clique.epoch");
            Assert.AreEqual((UInt256?)UInt256.Zero, chainSpec.Clique.Reward, "Clique.reward");

            Assert.AreEqual((long?)1, chainSpec.HomesteadBlockNumber, "homestead no");
            Assert.AreEqual((long?)2, chainSpec.TangerineWhistleBlockNumber, "tw no");
            Assert.AreEqual((long?)3, chainSpec.SpuriousDragonBlockNumber, "sd no");
            Assert.AreEqual((long?)4, chainSpec.ByzantiumBlockNumber, "byzantium no");
            Assert.AreEqual((long?)5, chainSpec.ConstantinopleBlockNumber, "constantinople no");
            Assert.AreEqual(null, chainSpec.DaoForkBlockNumber, "dao no");
        }
Beispiel #22
0
        public void TransactionsHaveChangedMessageReceived_TransactionsAdded()
        {
            // Arrange
            var viewModel = this.AutoMockContainer.Create <TransactionsViewModel>();
            var transactionsHaveChangedMessageHandler = viewModel as IMessageHandler <TransactionsHaveChangedMessage>;

            var hash         = UInt256.Parse("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF");
            var transactions = new List <TransactionItem>
            {
                new TransactionItem(hash, TransactionType.ContractTransaction, uint.MinValue, DateTime.Now)
            };

            // Act
            var transactionsCount = viewModel.Transactions.Count;

            transactionsHaveChangedMessageHandler.HandleMessage(new TransactionsHaveChangedMessage(transactions));

            // Assert
            Assert.Equal(0, transactionsCount);
            Assert.Single(viewModel.Transactions);
        }
Beispiel #23
0
        public void TestTargetToBits()
        {
            var target1   = UInt256.Parse("404cb000000000000000000000000000000000000000000000000", NumberStyles.HexNumber);
            var expected1 = 0x1b0404cbU;
            var actual1   = DataCalculator.TargetToBits(target1);

            Assert.AreEqual(expected1, actual1);

            // difficulty: 1
            var target2   = UInt256.Parse("ffff0000000000000000000000000000000000000000000000000000", NumberStyles.HexNumber);
            var expected2 = 0x1d00ffffU;
            var actual2   = DataCalculator.TargetToBits(target2);

            Assert.AreEqual(expected2, actual2);

            var target3   = UInt256.Parse("7fff0000000000000000000000000000000000000000000000000000", NumberStyles.HexNumber);
            var expected3 = 0x1c7fff00U;
            var actual3   = DataCalculator.TargetToBits(target3);

            Assert.AreEqual(expected3, actual3);
        }
Beispiel #24
0
        internal bool Load(DataNode root)
        {
            this.timestamp     = root.GetUInt32("timestamp");
            this.consensusData = root.GetUInt32("consensusData");
            this.hash          = UInt256.Parse(root.GetString("hash"));


            this._transactions.Clear();

            foreach (var child in root.Children)
            {
                if (child.Name == "transaction")
                {
                    var tx = new Transaction(this);
                    tx.Load(child);
                    _transactions.Add(tx);
                }
            }

            return(true);
        }
Beispiel #25
0
        public async Task AddBlock_ValidBlockNotInBlockPoolInBlockChainWithTheRightBlockHeaderType_BlockAddedToBlockPool()
        {
            var block = new Block
            {
                PreviousBlockHash = UInt256.Zero,
                Hash          = UInt256.Parse("d4dab99ed65c3655a9619b215ab1988561b706b6e5196b6e0ada916aa6601622"),
                NextConsensus = UInt160.Zero,
                Transactions  = new Transaction[]
                {
                    new ContractTransaction
                    {
                        Hash = UInt256.Parse("1a259dba256600620c6c91094f3a300b30f0cbaecee19c6114deffd3288957d7")
                    }
                }
            };

            var expectedBlockHeader = new BlockHeader(HeaderType.Header)
            {
                Hash = block.Hash
            };

            var blockPoolMock = this.AutoMockContainer.GetMock <IBlockPool>();

            blockPoolMock
            .Setup(x => x.TryAdd(block))
            .Returns(false);

            var repositoryMock = this.AutoMockContainer.GetMock <IRepository>();

            repositoryMock
            .Setup(x => x.GetBlockHeader(block.Hash))
            .ReturnsAsync(expectedBlockHeader);

            var testee = this.AutoMockContainer.Create <BlockProcessor>();

            await testee.AddBlock(block);

            blockPoolMock
            .Verify(x => x.TryAdd(block));
        }
Beispiel #26
0
        private void button3_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex < 0)
            {
                return;
            }
            if (listBox2.SelectedIndex < 0)
            {
                return;
            }
            byte[] parameter;
            ContractParameterType type = (ContractParameterType)listBox2.SelectedItem;

            switch (type)
            {
            case ContractParameterType.Integer:
                parameter = BigInteger.Parse(textBox2.Text).ToByteArray();
                break;

            case ContractParameterType.Hash160:
                parameter = UInt160.Parse(textBox2.Text).ToArray();
                break;

            case ContractParameterType.Hash256:
                parameter = UInt256.Parse(textBox2.Text).ToArray();
                break;

            default:
                parameter = textBox2.Text.HexToBytes();
                break;
            }
            Contract contract = Program.CurrentWallet.GetContract(Wallet.ToScriptHash((string)listBox1.SelectedItem));

            if (!context.Add(contract, listBox2.SelectedIndex, parameter))
            {
                throw new InvalidOperationException();
            }
            textBox1.Text   = textBox2.Text;
            button4.Visible = context.Completed;
        }
Beispiel #27
0
 /// <summary>
 /// 将钱包内的资产转账到指定地址
 /// </summary>
 /// <param name="_params[0]">收款地址</param>
 /// <param name="_params[1]">资产ID</param>
 /// <param name="_params[2]">bhp手续费地址,可选参数。(转账资产包含BHP时,此参数无效)</param>
 /// <returns>交易</returns>
 private JObject SendToCold(JArray _params)
 {
     if (wallet == null || walletTimeLock.IsLocked())
     {
         throw new RpcException(-400, "Access denied");
     }
     else
     {
         UInt160            scriptHash  = _params[0].AsString().ToScriptHash();
         UInt256            assetId     = _params.Count >= 2 ? UInt256.Parse(_params[1].AsString()) : Blockchain.GoverningToken.Hash;
         UInt160            fee_address = _params.Count >= 3 ? _params[2].AsString().ToScriptHash() : null;
         IEnumerable <Coin> allCoins    = wallet.FindUnspentCoins();
         Coin[]             coins       = TransactionContract.FindUnspentCoins(allCoins, assetId);
         Transaction        tx          = MakeToColdTransaction(coins, scriptHash, assetId, fee_address);
         if (tx == null)
         {
             throw new RpcException(-300, "Insufficient funds");
         }
         ContractParametersContext context = new ContractParametersContext(tx);
         wallet.Sign(context);
         if (context.Completed)
         {
             tx.Witnesses = context.GetWitnesses();
             if (tx.Size > Transaction.MaxTransactionSize)
             {
                 throw new RpcException(-301, "The size of the free transaction must be less than 102400 bytes");
             }
             wallet.ApplyTransaction(tx);
             system.LocalNode.Tell(new LocalNode.Relay {
                 Inventory = tx
             });
             return(tx.ToJson());
         }
         else
         {
             return(context.ToJson());
         }
     }
 }
Beispiel #28
0
        public void TestGetBlock()
        {
            var snapshot = Blockchain.Singleton.GetSnapshot();
            var tx1      = TestUtils.GetTransaction();

            tx1.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01 };
            var state1 = new TransactionState
            {
                Transaction = tx1,
                BlockIndex  = 1
            };
            var tx2 = TestUtils.GetTransaction();

            tx2.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x02 };
            var state2 = new TransactionState
            {
                Transaction = tx2,
                BlockIndex  = 1
            };

            snapshot.Transactions.Add(tx1.Hash, state1);
            snapshot.Transactions.Add(tx2.Hash, state2);

            TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction();

            tblock.Hashes = new UInt256[] { tx1.Hash, tx2.Hash };
            Block block = tblock.GetBlock(snapshot.Transactions);

            block.Index.Should().Be(1);
            block.MerkleRoot.Should().Be(UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff02"));
            block.Transactions.Length.Should().Be(1);
            block.Transactions[0].Hash.Should().Be(tx2.Hash);
        }
Beispiel #29
0
        public static void SignAndShowInformation(Transaction tx)
        {
            if (tx == null)
            {
                MessageBox.Show(Strings.InsufficientFunds);
                return;
            }
            if (tx.Attributes.All(p => p.Usage != TransactionAttributeUsage.Vote) && tx.Outputs.Any(p => p.AssetId.Equals(Blockchain.AntShare.Hash)) && Settings.Default.Votes.Count > 0)
            {
                tx.Attributes = tx.Attributes.Concat(Settings.Default.Votes.OfType <string>().Select(p => new TransactionAttribute
                {
                    Usage = TransactionAttributeUsage.Vote,
                    Data  = UInt256.Parse(p).ToArray()
                })).ToArray();
            }
            SignatureContext context;

            try
            {
                context = new SignatureContext(tx);
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show(Strings.UnsynchronizedBlock);
                return;
            }
            Program.CurrentWallet.Sign(context);
            if (context.Completed)
            {
                context.Signable.Scripts = context.GetScripts();
                Program.CurrentWallet.SaveTransaction(tx);
                Program.LocalNode.Relay(tx);
                InformationBox.Show(tx.Hash.ToString(), Strings.SendTxSucceedMessage, Strings.SendTxSucceedTitle);
            }
            else
            {
                InformationBox.Show(context.ToString(), Strings.IncompletedSignatureMessage, Strings.IncompletedSignatureTitle);
            }
        }
Beispiel #30
0
        public void TestGetBlock()
        {
            var cache = new TestDataCache <UInt256, TransactionState>();
            var tx1   = TestUtils.GetTransaction();

            tx1.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01 };
            var state1 = new TransactionState
            {
                Transaction = tx1,
                BlockIndex  = 1
            };
            var tx2 = TestUtils.GetTransaction();

            tx2.Script = new byte[] { 0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x01,
                                      0x01, 0x01, 0x01, 0x02 };
            var state2 = new TransactionState
            {
                Transaction = tx2,
                BlockIndex  = 1
            };

            cache.Add(tx1.Hash, state1);
            cache.Add(tx2.Hash, state2);

            TrimmedBlock tblock = GetTrimmedBlockWithNoTransaction();

            tblock.Hashes = new UInt256[] { tx1.Hash, tx2.Hash };
            Block block = tblock.GetBlock(cache);

            block.Index.Should().Be(1);
            block.MerkleRoot.Should().Be(UInt256.Parse("0xa400ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff02"));
            block.Transactions.Length.Should().Be(1);
            block.Transactions[0].Hash.Should().Be(tx2.Hash);
        }