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"]); }
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; }
public WorldInformation(Bencodex.Types.Dictionary serialized) { _worlds = serialized.ToDictionary( kv => kv.Key.ToInteger(), kv => new World((Bencodex.Types.Dictionary)kv.Value) ); }
public RankingState(Bencodex.Types.Dictionary bdict) : base(Address) { _map = bdict.ToDictionary( pair => new Address(pair.Key.EncodeAsByteArray()), pair => (long)(Bencodex.Types.Integer)pair.Value ); }
public Item(Bencodex.Types.Dictionary serialized) { item = ItemFactory.Deserialize( (Bencodex.Types.Dictionary)serialized["item"] ); count = (int)((Integer)serialized["count"]).Value; }
/// <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); }
public CollectionMap(Bencodex.Types.Dictionary serialized) { _dictionary = serialized.ToDictionary( kv => kv.Key.ToInteger(), kv => kv.Value.ToInteger() ); }
/// <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 ); } }
public BoundPeer(Bencodex.Types.Dictionary dictionary) : base(dictionary) { EndPoint = new DnsEndPoint( (Text)dictionary[EndPointHostKey], (Integer)dictionary[EndPointPortKey]); }
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"]; }
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; } }
/// <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; }
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(); }
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) ); }
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(); }
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"]), }); }
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) ) ); }
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"); }
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"]; }
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)); }
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(); } }
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; }
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));
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()); }
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; }
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; }
/// <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); }
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; }
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(); } }
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,