Пример #1
0
 public Row(Bencodex.Types.Dictionary serialized)
 {
     Id            = (Integer)serialized["item_id"];
     ItemSubType   = (ItemSubType)Enum.Parse(typeof(ItemSubType), (Bencodex.Types.Text)serialized["item_sub_type"]);
     Grade         = (Integer)serialized["grade"];
     ElementalType = (ElementalType)Enum.Parse(typeof(ElementalType), (Bencodex.Types.Text)serialized["elemental_type"]);
 }
Пример #2
0
        public BlockHeader(Bencodex.Types.Dictionary dict)
        {
            Index           = dict.GetValue <Integer>(IndexKey);
            Timestamp       = dict.GetValue <Text>(TimestampKey);
            Difficulty      = dict.GetValue <Integer>(DifficultyKey);
            TotalDifficulty = dict.GetValue <Integer>(TotalDifficultyKey);
            Nonce           = dict.GetValue <Binary>(NonceKey).ToImmutableArray();

            Miner = dict.ContainsKey((IKey)(Binary)MinerKey)
                ? dict.GetValue <Binary>(MinerKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;

            PreviousHash = dict.ContainsKey((IKey)(Binary)PreviousHashKey)
                ? dict.GetValue <Binary>(PreviousHashKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;

            TxHash = dict.ContainsKey((IKey)(Binary)TxHashKey)
                ? dict.GetValue <Binary>(TxHashKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;

            Hash = dict.ContainsKey((IKey)(Binary)HashKey)
                ? dict.GetValue <Binary>(HashKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;

            PreEvaluationHash = dict.ContainsKey((IKey)(Binary)PreEvaluationHashKey)
                ? dict.GetValue <Binary>(PreEvaluationHashKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;

            StateRootHash = dict.ContainsKey((IKey)(Binary)StateRootHashKey)
                ? dict.GetValue <Binary>(StateRootHashKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;
        }
Пример #3
0
 public WorldInformation(Bencodex.Types.Dictionary serialized)
 {
     _worlds = serialized.ToDictionary(
         kv => kv.Key.ToInteger(),
         kv => new World((Bencodex.Types.Dictionary)kv.Value)
         );
 }
Пример #4
0
 public RankingState(Bencodex.Types.Dictionary bdict) : base(Address)
 {
     _map = bdict.ToDictionary(
         pair => new Address(pair.Key.EncodeAsByteArray()),
         pair => (long)(Bencodex.Types.Integer)pair.Value
         );
 }
Пример #5
0
 public Item(Bencodex.Types.Dictionary serialized)
 {
     item = ItemFactory.Deserialize(
         (Bencodex.Types.Dictionary)serialized["item"]
         );
     count = (int)((Integer)serialized["count"]).Value;
 }
Пример #6
0
        /// <inheritdoc/>
        public override void SetBlockStates(
            HashDigest <SHA256> blockHash,
            IImmutableDictionary <string, IValue> states)
        {
            var serialized = new Bencodex.Types.Dictionary(
                states.ToImmutableDictionary(
                    kv => (IKey)(Text)kv.Key,
                    kv => kv.Value
                    )
                );

            UPath path    = StatePath(blockHash);
            UPath dirPath = path.GetDirectory();

            CreateDirectoryRecursively(_states, dirPath);

            var codec = new Codec();

            using Stream file = _states.CreateFile(path);
            if (_compress)
            {
                using var deflate = new DeflateStream(file, CompressionLevel.Fastest, true);
                codec.Encode(serialized, deflate);
            }
            else
            {
                codec.Encode(serialized, file);
            }

            _statesCache.AddOrUpdate(blockHash, states);
        }
Пример #7
0
 public CollectionMap(Bencodex.Types.Dictionary serialized)
 {
     _dictionary = serialized.ToDictionary(
         kv => kv.Key.ToInteger(),
         kv => kv.Value.ToInteger()
         );
 }
Пример #8
0
        /// <inheritdoc/>
        public override void SetBlockStates(
            HashDigest <SHA256> blockHash,
            IImmutableDictionary <Address, IValue> states)
        {
            _statesCache.AddOrUpdate(blockHash, states);
            var serialized = new Bencodex.Types.Dictionary(
                states.Select(kv =>
                              new KeyValuePair <IKey, IValue>(
                                  new Binary(kv.Key.ToByteArray()),
                                  kv.Value
                                  )
                              )
                );

            using (var stream = new MemoryStream())
            {
                _codec.Encode(serialized, stream);
                stream.Seek(0, SeekOrigin.Begin);
                UploadFile(
                    BlockStateFileId(blockHash),
                    ByteUtil.Hex(blockHash.ToByteArray()),
                    stream
                    );
            }
        }
Пример #9
0
 public BoundPeer(Bencodex.Types.Dictionary dictionary)
     : base(dictionary)
 {
     EndPoint = new DnsEndPoint(
         (Text)dictionary[EndPointHostKey],
         (Integer)dictionary[EndPointPortKey]);
 }
Пример #10
0
 public Row(Bencodex.Types.Dictionary serialized) : base(serialized)
 {
     SetId             = (Integer)serialized["set_id"];
     Stat              = serialized["stat"].ToDecimalStat();
     AttackRange       = serialized["attack_range"].ToDecimal();
     SpineResourcePath = (Text)serialized["spine_resource_path"];
 }
Пример #11
0
        public static AttachmentActionResult Deserialize(BxDictionary serialized)
        {
            var typeId = ((BxText)serialized["typeId"]).Value;
            Func <BxDictionary, AttachmentActionResult> deserializer;

            try
            {
                deserializer = Deserializers[typeId];
            }
            catch (KeyNotFoundException)
            {
                var typeIds = string.Join(
                    ", ",
                    Deserializers.Keys.OrderBy(k => k, StringComparer.InvariantCulture)
                    );
                throw new ArgumentException(
                          $"Unregistered typeId: {typeId}; available typeIds: {typeIds}"
                          );
            }

            try
            {
                return(deserializer(serialized));
            }
            catch (Exception e)
            {
                Log.Error(
                    "{FullName} was raised during deserialize: {Serialized}",
                    e.GetType().FullName,
                    serialized);
                throw;
            }
        }
Пример #12
0
 /// <summary>
 /// Creates <see cref="BlockDigest"/> instance from
 /// <see cref="Bencodex.Types.Dictionary"/> representation of the <see cref="Block{T}"/>.
 /// </summary>
 /// <param name="dict">
 /// <see cref="Bencodex.Types.Dictionary"/> representation of the <see cref="Block{T}"/>.
 /// </param>
 public BlockDigest(Bencodex.Types.Dictionary dict)
 {
     Header = new BlockHeader(dict.GetValue <Bencodex.Types.Dictionary>(HeaderKey));
     TxIds  = dict.ContainsKey((Binary)TransactionIdsKey)
         ? dict.GetValue <Bencodex.Types.List>(TransactionIdsKey)
              .Select(txId => ((Binary)txId).ToImmutableArray()).ToImmutableArray()
         : ImmutableArray <ImmutableArray <byte> > .Empty;
 }
Пример #13
0
 public ResultModel(Bencodex.Types.Dictionary serialized)
     : base(serialized)
 {
     id = serialized["id"].ToGuid();
     materialItemIdList = serialized["materialItemIdList"].ToList(StateExtensions.ToGuid);
     gold        = serialized["gold"].ToBigInteger();
     actionPoint = serialized["actionPoint"].ToInteger();
 }
Пример #14
0
        public SessionState(Bencodex.Types.Dictionary bdict) : base(Address)
        {
            var rawSessions = (Bencodex.Types.Dictionary)bdict["sessions"];

            sessions = rawSessions.ToDictionary(
                kv => kv.Key.ToString(),
                kv => new GameState((Bencodex.Types.Dictionary)kv.Value)
                );
        }
Пример #15
0
 public PurchaseInfo(Bencodex.Types.Dictionary serialized)
 {
     TradableId          = serialized[TradableIdKey].ToGuid();
     OrderId             = serialized[OrderIdKey].ToGuid();
     SellerAvatarAddress = serialized[SellerAvatarAddressKey].ToAddress();
     SellerAgentAddress  = serialized[SellerAgentAddressKey].ToAddress();
     ItemSubType         = serialized[ItemSubTypeKey].ToEnum <ItemSubType>();
     Price = serialized[PriceKey].ToFungibleAssetValue();
 }
Пример #16
0
 public static Row Deserialize(Bencodex.Types.Dictionary serialized)
 {
     return(new Row
     {
         Id = (int)((Integer)serialized["Id"]),
         Goal = (int)((Integer)serialized["Goal"]),
         QuestRewardId = (int)((Integer)serialized["QuestRewardId"]),
     });
 }
Пример #17
0
 public RankingState(Bencodex.Types.Dictionary serialized) : base(serialized)
 {
     _map = ((Bencodex.Types.Dictionary)serialized["map"]).ToDictionary(
         kv1 => kv1.Key.ToString_(),
         kv1 => ((Bencodex.Types.Dictionary)kv1.Value).ToDictionary(
             kv2 => kv2.Key.ToAddress(),
             kv2 => new RankingInfo((Bencodex.Types.Dictionary)kv2.Value)
             )
         );
 }
Пример #18
0
 public World(Bencodex.Types.Dictionary serialized)
 {
     Id                     = serialized.GetInteger("Id");
     Name                   = serialized.GetString("Name");
     StageBegin             = serialized.GetInteger("StageBegin");
     StageEnd               = serialized.GetInteger("StageEnd");
     UnlockedBlockIndex     = serialized.GetLong("UnlockedBlockIndex");
     StageClearedBlockIndex = serialized.GetLong("StageClearedBlockIndex");
     StageClearedId         = serialized.GetInteger("StageClearedId");
 }
Пример #19
0
 public Row(Bencodex.Types.Dictionary serialized)
 {
     Id            = (Bencodex.Types.Integer)serialized["id"];
     ElementalType = (ElementalType)Enum.Parse(typeof(ElementalType),
                                               (Bencodex.Types.Text)serialized["elemental_type"]);
     SkillType       = (SkillType)Enum.Parse(typeof(SkillType), (Bencodex.Types.Text)serialized["skill_type"]);
     SkillCategory   = (SkillCategory)Enum.Parse(typeof(SkillCategory), (Bencodex.Types.Text)serialized["skill_category"]);
     SkillTargetType = (SkillTargetType)Enum.Parse(typeof(SkillTargetType), (Bencodex.Types.Text)serialized["skill_target_type"]);
     HitCount        = (Bencodex.Types.Integer)serialized["hit_count"];
     Cooldown        = (Bencodex.Types.Integer)serialized["cooldown"];
 }
Пример #20
0
        public static Currency Deserialize(Bencodex.Types.Dictionary serialized)
        {
            IImmutableSet <Address> minters = null;

            if (serialized["minters"] is Bencodex.Types.List mintersAsList)
            {
                minters = mintersAsList.Select(b => new Address(((Binary)b).ByteArray)).ToImmutableHashSet();
            }

            return(new Currency((Text)serialized["ticker"], ((Binary)serialized["decimalPlaces"]).First(), minters));
        }
Пример #21
0
 public Item(Bencodex.Types.Dictionary serialized)
 {
     item = ItemFactory.Deserialize(
         (Bencodex.Types.Dictionary)serialized["item"]
         );
     count = (int)((Integer)serialized["count"]).Value;
     if (serialized.ContainsKey("l"))
     {
         Lock = serialized["l"].ToLock();
     }
 }
Пример #22
0
        public RawTransaction(Bencodex.Types.Dictionary dict)
        {
            Nonce            = dict.GetValue <Integer>(NonceKey);
            Signer           = dict.GetValue <Binary>(SignerKey).ToImmutableArray();
            UpdatedAddresses = dict.GetValue <Bencodex.Types.List>(UpdatedAddressesKey)
                               .Select(value => ((Binary)value).ToImmutableArray()).ToImmutableArray();
            PublicKey = dict.GetValue <Binary>(PublicKeyKey).ToImmutableArray();
            Timestamp = dict.GetValue <Text>(TimestampKey);
            Actions   = dict.GetValue <Bencodex.Types.List>(ActionsKey).ToImmutableArray();

            Signature = dict.ContainsKey((Binary)SignatureKey)
                ? dict.GetValue <Binary>(SignatureKey).ToImmutableArray()
                : ImmutableArray <byte> .Empty;
        }
Пример #23
0
 public void MakeCandidateData()
 {
     Bencodex.Types.Dictionary expectedGenesis = Bencodex.Types.Dictionary.Empty
                                                 .Add("index", 0L)
                                                 .Add("timestamp", "2021-09-06T04:46:39.123000Z")
                                                 .Add("difficulty", 0L)
                                                 .Add("total_difficulty", 0)
                                                 .Add("nonce", ImmutableArray <byte> .Empty)
                                                 .Add(
         "public_key",
         ParseHex("0200e02709cc0c051dc105188c454a2e7ef7b36b85da34529d3abc1968167cf54f")
         )
                                                 .Add("protocol_version", 3);
     AssertBencodexEqual(expectedGenesis, GenesisMetadata.MakeCandidateData(default));
Пример #24
0
        public GameState(Bencodex.Types.Dictionary bdict) : base(Address)
        {
            var rawSessionID = (Bencodex.Types.Text)bdict["sessionID"];
            var rawTurn      = (Integer)bdict["turn"];
            var rawWinner    = (Bencodex.Types.Binary)bdict["winner"];
            var rawPlayers   = (Bencodex.Types.List)bdict["players"];
            var rawGameBoard = (Bencodex.Types.List)bdict["gameBoard"];

            SessionID = rawSessionID.Value;
            Turn      = rawTurn.ToInt();
            Winner    = new Address(rawWinner);
            Players   = rawPlayers.ToList(value => new Address((Binary)value));
            GameBoard = rawGameBoard.ToList(value => value.ToInt());
        }
Пример #25
0
        public BlockDigest(Bencodex.Types.Dictionary dict)
        {
            var headerDict = dict.GetValue <Bencodex.Types.Dictionary>(HeaderKey);
            var tuple      = BlockMarshaler.UnmarshalPreEvaluationBlockHeader(headerDict);

            _metadata          = tuple.Metadata;
            _nonce             = tuple.Nonce;
            _preEvaluationHash = tuple.PreEvaluationHash;
            StateRootHash      = BlockMarshaler.UnmarshalBlockHeaderStateRootHash(headerDict);
            Signature          = BlockMarshaler.UnmarshalBlockHeaderSignature(headerDict);
            Hash  = BlockMarshaler.UnmarshalBlockHeaderHash(headerDict);
            TxIds = dict.ContainsKey((IKey)(Binary)TransactionIdsKey)
                ? dict.GetValue <Bencodex.Types.List>(TransactionIdsKey)
                    .Select(txId => ((Binary)txId).ToImmutableArray()).ToImmutableArray()
                : ImmutableArray <ImmutableArray <byte> > .Empty;
        }
Пример #26
0
 protected AttachmentActionResult(BxDictionary serialized)
 {
     itemUsable = serialized.ContainsKey("itemUsable")
        ? (ItemUsable)ItemFactory.Deserialize((BxDictionary)serialized["itemUsable"])
        : null;
     costume = serialized.ContainsKey("costume")
         ? (Costume)ItemFactory.Deserialize((BxDictionary)serialized["costume"])
         : null;
     tradableFungibleItem = serialized.ContainsKey("tradableFungibleItem")
         ? (ITradableFungibleItem)ItemFactory.Deserialize(
         (BxDictionary)serialized["tradableFungibleItem"])
         : null;
     tradableFungibleItemCount = serialized.ContainsKey("tradableFungibleItemCount")
         ? serialized["tradableFungibleItemCount"].ToInteger()
         : default;
 }
Пример #27
0
        /// <inheritdoc/>
        public override void SetBlockStates(
            HashDigest <SHA256> blockHash,
            IImmutableDictionary <string, IValue> states)
        {
            var serialized = new Bencodex.Types.Dictionary(
                states.ToImmutableDictionary(
                    kv => (IKey)(Text)kv.Key,
                    kv => kv.Value
                    )
                );

            byte[] key = BlockStateKey(blockHash);

            var codec = new Codec();

            byte[] value = codec.Encode(serialized);

            _stateDb.Put(key, value);
            _statesCache.AddOrUpdate(blockHash, states);
        }
Пример #28
0
        public RawBlock(Bencodex.Types.Dictionary dict)
        {
            Index        = dict.GetValue <Integer>(IndexKey);
            Timestamp    = dict.GetValue <Text>(TimestampKey);
            Difficulty   = dict.GetValue <Integer>(DifficultyKey);
            Transactions = dict.GetValue <Bencodex.Types.List>(TransactionsKey)
                           .Select(tx => (byte[])(Binary)tx);
            Nonce = dict.GetValue <Binary>(NonceKey);

            Miner = dict.ContainsKey((Binary)RewardBeneficiaryKey)
                ? dict.GetValue <Binary>(RewardBeneficiaryKey)
                : null;

            PreviousHash = dict.ContainsKey((Binary)PreviousHashKey)
                ? (byte[])dict.GetValue <Binary>(PreviousHashKey)
                : null;

            Hash = dict.ContainsKey((Binary)HashKey)
                ? (byte[])dict.GetValue <Binary>(HashKey)
                : null;
        }
Пример #29
0
        public InitializeStates(
            RankingState0 rankingState,
            ShopState shopState,
            Dictionary <string, string> tableSheets,
            GameConfigState gameConfigState,
            RedeemCodeState redeemCodeState,
            AdminState adminAddressState,
            ActivatedAccountsState activatedAccountsState,
            GoldCurrencyState goldCurrencyState,
            GoldDistribution[] goldDistributions,
            PendingActivationState[] pendingActivationStates,
            AuthorizedMinersState authorizedMinersState = null,
            CreditsState creditsState = null)
        {
            Ranking           = (Bencodex.Types.Dictionary)rankingState.Serialize();
            Shop              = (Bencodex.Types.Dictionary)shopState.Serialize();
            TableSheets       = tableSheets;
            GameConfig        = (Bencodex.Types.Dictionary)gameConfigState.Serialize();
            RedeemCode        = (Bencodex.Types.Dictionary)redeemCodeState.Serialize();
            AdminAddress      = (Bencodex.Types.Dictionary)adminAddressState.Serialize();
            ActivatedAccounts = (Bencodex.Types.Dictionary)activatedAccountsState.Serialize();
            GoldCurrency      = (Bencodex.Types.Dictionary)goldCurrencyState.Serialize();
            GoldDistributions = new Bencodex.Types.List(
                goldDistributions.Select(d => d.Serialize()).Cast <Bencodex.Types.IValue>()
                );
            PendingActivations = new Bencodex.Types.List(pendingActivationStates.Select(p => p.Serialize()));

            if (!(authorizedMinersState is null))
            {
                AuthorizedMiners = (Bencodex.Types.Dictionary)authorizedMinersState.Serialize();
            }

            if (!(creditsState is null))
            {
                Credits = (Bencodex.Types.Dictionary)creditsState.Serialize();
            }
        }
Пример #30
0
        internal ImmutableList <Transaction <T> > GatherTransactionsToMine(
            BlockMetadata metadata,
            long maxBlockBytes,
            int maxTransactions,
            int maxTransactionsPerSigner,
            IComparer <Transaction <T> > txPriority = null
            )
        {
            long index = Count;
            ImmutableList <Transaction <T> > stagedTransactions = ListStagedTransactions(txPriority);

            _logger.Information(
                "Gathering transactions to mine for block #{Index} from {TxCount} " +
                "staged transactions...",
                index,
                stagedTransactions.Count);

            var transactionsToMine = new List <Transaction <T> >();

            // FIXME: The tx collection timeout should be configurable.
            DateTimeOffset timeout = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(4);

            // FIXME: Possibly better to not directly refer to policy.
            HashAlgorithmType hashAlgorithm = Policy.GetHashAlgorithm(index);

            // Makes an empty block payload to estimate the length of bytes without transactions.
            // FIXME: We'd better to estimate only transactions rather than the whole block.
            var dumbSig = metadata.PublicKey is null
                ? (ImmutableArray <byte>?)null
                : ImmutableArray.Create(new byte[71]);

            Bencodex.Types.Dictionary marshaledEmptyBlock = MarshalBlock(
                marshaledBlockHeader: MarshalBlockHeader(
                    marshaledPreEvaluatedBlockHeader: MarshalPreEvaluationBlockHeader(
                        marshaledMetadata: MarshalBlockMetadata(metadata),
                        nonce: default,