Exemplo n.º 1
0
        public void TransactionsWithInconsistentGenesisHashes()
        {
            var key = PrivateKey.FromString(
                "2ed05de0b35d93e4ae801ae40c8bb4257a771ff67c1e5d1754562e4191953710"
                );
            var differentGenesisHash = BlockHash.FromString(
                "76942b42f99c28da02ed916ebd2fadb189415e8288a4bd87f9ae3594127b79e6"
                );
            var txWithDifferentGenesis = new Transaction <Arithmetic>(
                nonce: 0L,
                signer: key.ToAddress(),
                publicKey: key.PublicKey,
                genesisHash: differentGenesisHash,
                updatedAddresses: ImmutableHashSet <Address> .Empty,
                timestamp: new DateTimeOffset(2021, 9, 7, 12, 1, 12, 345, TimeSpan.FromHours(9)),
                actions: Array.Empty <Arithmetic>(),
                signature: ByteUtil.ParseHex(
                    "304402202027a31e4298c685daaa944b1d120b4e6894f3bfffa13563331c0a7071a04b" +
                    "310220167507575e982d47d7c6753b782a5f1beb6415af96e7db3ccaf83b516d5133d1"
                    )
                );
            BlockContent <Arithmetic> block = Block1.Copy();

            Transaction <Arithmetic>[] inconsistentTxs =
                block.Transactions.Append(txWithDifferentGenesis).ToArray();
            InvalidTxGenesisHashException e = Assert.Throws <InvalidTxGenesisHashException>(
                () => block.Transactions = inconsistentTxs
                );

            Assert.Equal(Block1.Transactions[0].GenesisHash, e.ExpectedGenesisHash);
            Assert.Equal(differentGenesisHash, e.ImproperGenesisHash);
            Assert.Equal(Block1.Transactions, block.Transactions);
        }
Exemplo n.º 2
0
        /// <inheritdoc cref="BaseStore.IterateBlockHashes()"/>
        public override IEnumerable <BlockHash> IterateBlockHashes()
        {
            foreach (UPath path in _blocks.EnumerateDirectories(UPath.Root))
            {
                string upper = path.GetName();
                if (upper.Length != 2)
                {
                    continue;
                }

                foreach (UPath subPath in _blocks.EnumerateFiles(path))
                {
                    string    lower = subPath.GetName();
                    string    name  = upper + lower;
                    BlockHash blockHash;
                    try
                    {
                        blockHash = BlockHash.FromString(name);
                    }
                    catch (Exception)
                    {
                        // Skip if a filename does not match to the format.
                        continue;
                    }

                    yield return(blockHash);
                }
            }
        }
Exemplo n.º 3
0
        public void FromString()
        {
            byte[] b =
            {
                0x28, 0x31, 0xd4, 0xc2, 0x4a, 0xe5, 0xd1, 0x93, 0x1a, 0x16, 0xde,
                0x0a, 0x06, 0x6e, 0x23, 0x3e, 0x0e, 0xed, 0x1d, 0x3f, 0xdf, 0x6d,
                0x57, 0x2a, 0xd5, 0x8d, 0x1c, 0x37, 0x05, 0xc8, 0xcb, 0xfc,
            };
            var       expected = new BlockHash(b);
            BlockHash actual   = BlockHash.FromString(
                "2831d4c24ae5d1931a16de0a066e233e0eed1d3fdf6d572ad58d1c3705c8cbfc"
                );

            Assert.Equal(expected, actual);

            Assert.Throws <ArgumentNullException>(() => BlockHash.FromString(null));
            Assert.Throws <ArgumentOutOfRangeException>(() => BlockHash.FromString(string.Empty));
            Assert.Throws <ArgumentOutOfRangeException>(() => BlockHash.FromString("abc"));
            Assert.Throws <ArgumentOutOfRangeException>(() => BlockHash.FromString("ab"));
            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        BlockHash.FromString(
                                                            "2831d4c24ae5d1931a16de0a066e233e0eed1d3fdf6d572ad58d1c3705c8cb"
                                                            )
                                                        );
            Assert.Throws <ArgumentOutOfRangeException>(() =>
                                                        BlockHash.FromString(
                                                            "2831d4c24ae5d1931a16de0a066e233e0eed1d3fdf6d572ad58d1c3705c8cbfc00"
                                                            )
                                                        );
            Assert.Throws <FormatException>(() => BlockHash.FromString("asdf"));
        }
Exemplo n.º 4
0
 public static BlockHash ParseBlockHash(string blockHash)
 {
     try
     {
         return(BlockHash.FromString(blockHash));
     }
     catch (Exception e) when(e is ArgumentOutOfRangeException || e is FormatException)
     {
         throw new CommandExitedException($"{blockHash}: {e.Message}", 1);
     }
 }
Exemplo n.º 5
0
        public void Sign(
            [Argument("PRIVATE-KEY", Description = "A hex-encoded private key for signing.")] string privateKey,
            [Argument("NONCE", Description = "A nonce for new transaction.")] long nonce,
            [Argument("GENESIS-HASH", Description = "A hex-encoded genesis block hash.")] string genesisHash,
            [Argument("TIMESTAMP", Description = "A datetime for new transaction.")] string timestamp,
            [Option("action", new[] { 'a' }, Description = "A path of the file contained base64 encoded actions.")] string[] actions
            )
        {
            List <NCAction> parsedActions = actions.Select(a =>
            {
                if (File.Exists(a))
                {
                    a = File.ReadAllText(a);
                }

                var decoded           = (List)Codec.Decode(Convert.FromBase64String(a));
                string type           = (Text)decoded[0];
                Dictionary plainValue = (Dictionary)decoded[1];

                ActionBase action = type switch
                {
                    nameof(ActivateAccount) => new ActivateAccount(),
                    nameof(MonsterCollect) => new MonsterCollect(),
                    nameof(ClaimMonsterCollectionReward) => new ClaimMonsterCollectionReward(),
                    nameof(TransferAsset) => new TransferAsset(),
                    _ => throw new CommandExitedException($"Unsupported action type was passed '{type}'", 128)
                };
                action.LoadPlainValue(plainValue);

                return((NCAction)action);
            }).ToList();

            Transaction <NCAction> tx = Transaction <NCAction> .Create(
                nonce : nonce,
                privateKey : new PrivateKey(ByteUtil.ParseHex(privateKey)),
                genesisHash : BlockHash.FromString(genesisHash),
                timestamp : DateTimeOffset.Parse(timestamp),
                actions : parsedActions
                );

            byte[] raw = tx.Serialize(true);

            _console.Out.WriteLine(Convert.ToBase64String(raw));
        }
Exemplo n.º 6
0
        public BlockQuery()
        {
            Field <NonNullGraphType <ListGraphType <NonNullGraphType <BlockType <T> > > > >(
                "blocks",
                arguments: new QueryArguments(
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "desc",
                DefaultValue = false,
            },
                    new QueryArgument <IntGraphType>
            {
                Name         = "offset",
                DefaultValue = 0,
            },
                    new QueryArgument <IntGraphType> {
                Name = "limit"
            },
                    new QueryArgument <BooleanGraphType>
            {
                Name         = "excludeEmptyTxs",
                DefaultValue = false,
            },
                    new QueryArgument <AddressType> {
                Name = "miner"
            }
                    ),
                resolve: context =>
            {
                bool desc            = context.GetArgument <bool>("desc");
                long offset          = context.GetArgument <long>("offset");
                int?limit            = context.GetArgument <int?>("limit", null);
                bool excludeEmptyTxs = context.GetArgument <bool>("excludeEmptyTxs");
                Address?miner        = context.GetArgument <Address?>("miner", null);
                return(ExplorerQuery <T> .ListBlocks(desc, offset, limit, excludeEmptyTxs, miner));
            }
                );

            Field <BlockType <T> >(
                "block",
                arguments: new QueryArguments(
                    new QueryArgument <IdGraphType> {
                Name = "hash"
            },
                    new QueryArgument <IdGraphType> {
                Name = "index"
            }
                    ),
                resolve: context =>
            {
                string hash = context.GetArgument <string>("hash");
                long?index  = context.GetArgument <long?>("index", null);

                if (!(hash is null ^ index is null))
                {
                    throw new GraphQL.ExecutionError(
                        "The parameters hash and index are mutually exclusive; " +
                        "give only one at a time.");
                }

                if (hash is string hashNotNull)
                {
                    return(ExplorerQuery <T> .GetBlockByHash(BlockHash.FromString(hashNotNull)));
                }

                if (index is long indexNotNull)
                {
                    return(ExplorerQuery <T> .GetBlockByIndex(indexNotNull));
                }

                throw new GraphQL.ExecutionError("Unexpected block query");
            }
 private static BlockHash H(string h) => BlockHash.FromString(h);
Exemplo n.º 8
0
        public BlockContentFixture()
        {
            TimeSpan kst = TimeSpan.FromHours(9);

            GenesisKey = new PrivateKey(new byte[]
            {
                0x9b, 0xf4, 0x66, 0x4b, 0xa0, 0x9a, 0x89, 0xfa, 0xeb, 0x68, 0x4b,
                0x94, 0xe6, 0x9f, 0xfd, 0xe0, 0x1d, 0x26, 0xae, 0x14, 0xb5, 0x56,
                0x20, 0x4d, 0x3f, 0x6a, 0xb5, 0x8f, 0x61, 0xf7, 0x84, 0x18,
            });
            GenesisMetadata = new BlockMetadata
            {
                Index        = 0,
                Timestamp    = new DateTimeOffset(2021, 9, 6, 13, 46, 39, 123, kst),
                PublicKey    = GenesisKey.PublicKey,
                Difficulty   = 0,
                PreviousHash = null,
                TxHash       = null,
            };
            Genesis     = new BlockContent <Arithmetic>(GenesisMetadata);
            GenesisHash = BlockHash.FromString(
                "341e8f360597d5bc45ab96aabc5f1b0608063f30af7bd4153556c9536a07693a"
                );
            Block1Key = new PrivateKey(new byte[]
            {
                0xfc, 0xf3, 0x0b, 0x33, 0x3d, 0x04, 0xcc, 0xfe, 0xb5, 0x62, 0xf0,
                0x00, 0xa3, 0x2d, 0xf4, 0x88, 0xe7, 0x15, 0x49, 0x49, 0xd3, 0x1d,
                0xdc, 0xac, 0x3c, 0xf9, 0x27, 0x8a, 0xcb, 0x57, 0x86, 0xc7,
            });
            BlockMetadata1 = new BlockMetadata
            {
                Index        = 1,
                Timestamp    = new DateTimeOffset(2021, 9, 6, 17, 1, 9, 45, kst),
                PublicKey    = Block1Key.PublicKey,
                Difficulty   = 123,
                PreviousHash = GenesisHash,
                TxHash       = HashDigest <SHA256> .FromString(
                    "654698d34b6d9a55b0c93e4ffb2639278324868c91965bc5f96cb3071d6903a0"
                    ),
            };
            var block1Tx0Key = PrivateKey.FromString(
                "2d5c20079bc4b2e6eab9ecbb405da8ba6590c436edfb07b7d4466563d7dac096"
                );

            Tx0InBlock1 = new Transaction <Arithmetic>(
                nonce: 0L,
                signer: block1Tx0Key.ToAddress(),
                publicKey: block1Tx0Key.PublicKey,
                genesisHash: GenesisHash,
                updatedAddresses: ImmutableHashSet <Address> .Empty.Add(block1Tx0Key.ToAddress()),
                timestamp: new DateTimeOffset(2021, 9, 6, 17, 0, 1, 1, kst),
                actions: new[]
            {
                Arithmetic.Add(10), Arithmetic.Add(50), Arithmetic.Sub(25),
            },
                signature: ByteUtil.ParseHex(
                    "30440220422c85ea44845a56253654d95595ad06d6f09f862ca71b97e986ecbb453eac" +
                    "ae0220606e76276e40fa8f0795b880f712531fd6bd9db253bd8ab9c86aa4ab7d791d37"
                    )
                );
            Tx0InBlock1.Validate(block1Tx0Key);
            var block1Tx1Key = PrivateKey.FromString(
                "105341c78dfb0dd313b961081630444c2586a1f01fb0c625368ffdc9136cfa30"
                );

            Tx1InBlock1 = new Transaction <Arithmetic>(
                nonce: 1L,
                signer: block1Tx1Key.ToAddress(),
                publicKey: block1Tx1Key.PublicKey,
                genesisHash: GenesisHash,
                updatedAddresses: ImmutableHashSet <Address> .Empty.Add(block1Tx1Key.ToAddress()),
                timestamp: new DateTimeOffset(2021, 9, 6, 17, 0, 1, 1, kst),
                actions: new[] { Arithmetic.Add(30) },
                signature: ByteUtil.ParseHex(
                    "3045022100abe3caabf2a46a297f2e4496f2c46d7e2f723e75fc42025d19f3ed7fce382" +
                    "d4e02200ffd36f7bef759b6c7ab43bc0f8959a0c463f88fd0f1faeaa209a8661506c4f0"
                    )
                );
            Tx1InBlock1.Validate(block1Tx1Key);
            Block1 = new BlockContent <Arithmetic>(
                BlockMetadata1,
                new[]
            {
                Tx0InBlock1,
                Tx1InBlock1,
            }
                );
            BlockMetadataPv0 = new BlockMetadata
            {
                ProtocolVersion = 0,
                Index           = 0,
                Timestamp       = new DateTimeOffset(2021, 9, 6, 13, 46, 39, 123, kst),
                Miner           = GenesisKey.ToAddress(),
                Difficulty      = 0,
                PreviousHash    = null,
                TxHash          = null,
            };
            BlockPv0 = new BlockContent <Arithmetic>(BlockMetadataPv0);
            BlockPv1 = new BlockContent <Arithmetic>(Block1)
            {
                ProtocolVersion = 1,
                PublicKey       = null,
            };
            BlockMetadataPv1 = new BlockMetadata(BlockPv1);
        }