示例#1
0
        public void SerializationTests_FSharp_Collections()
        {
            var elements = new List <int>()
            {
                0, 1, 2
            };

            var mapElements = new List <Tuple <int, string> >()
            {
                new Tuple <int, string>(0, "zero"),
                new Tuple <int, string>(1, "one")
            };

            // F# list
            RoundtripSerializationTest(ListModule.Empty <int>());
            RoundtripSerializationTest(ListModule.OfSeq(elements));

            // F# set
            RoundtripSerializationTest(SetModule.Empty <int>());
            RoundtripSerializationTest(SetModule.OfSeq(elements));

            // F# map
            RoundtripSerializationTest(MapModule.OfSeq(new List <Tuple <int, string> >()));
            RoundtripSerializationTest(MapModule.OfSeq(mapElements));
        }
示例#2
0
        static FSharpChoice <FSharpList <Order>, Errors> ValidateOrders(IEnumerable <Order> orders)
        {
            var zero = ListModule.Empty <Order>().ReturnValidation();

            return(orders
                   .Select(ValidateOrder)
                   .Aggregate(zero, (e, c) => from a in e
                              join b in c on 1 equals 1
                              select a.Cons(b)));
        }
示例#3
0
 internal static CouchUrl Create(CouchRepo couchRepo, FSharpList <string> path, FSharpMap <string, string> queryString, FSharpList <CouchFilter> filters)
 {
     return(new CouchUrl()
     {
         couchRepo = couchRepo,
         path = path ?? ListModule.Empty <string>(),
         queryString = queryString ?? MapModule.Empty <string, string>(),
         filters = filters ?? ListModule.Empty <CouchFilter>()
     });
 }
示例#4
0
 public static ValueNode WinCol(
     AggregateType type,
     ValueNode aggregateParameter,
     IEnumerable <ValueNode> partitionBy     = null,
     IEnumerable <OrderByClauseNode> orderBy = null)
 {
     return(ValueNode.NewWindowedColumn(
                new Tuple <Tuple <AggregateType, ValueNode>, AST.WindowNode>(
                    new Tuple <AggregateType, ValueNode>(type, aggregateParameter),
                    new AST.WindowNode(
                        partitionBy == null ? ListModule.Empty <ValueNode>() : ListModule.OfSeq(partitionBy),
                        orderBy == null ? ListModule.Empty <OrderByClauseNode>() : ListModule.OfSeq(orderBy)))));
 }
示例#5
0
        public override IEnumerable <Types.ItemLocation> GetItemLocations(int Seed)
        {
            var rnd = new Random(Seed);

            var TheItems = Items.addReserves(3, Items.Items);

            TheItems = Items.addETanks(13, TheItems);
            TheItems = Items.addMissiles(33, TheItems);
            TheItems = Items.addSupers(13, TheItems);
            TheItems = Items.addPowerBombs(17, TheItems);

            var NewItems      = ListModule.Empty <Types.Item> ();
            var ItemLocations = ListModule.Empty <Types.ItemLocation> ();

            return(FullRandomizer.generateItems(rnd, ListModule.Empty <Types.Item> (),
                                                ListModule.Empty <Types.ItemLocation> (), TheItems, TournamentLocations.AllLocations));
        }
示例#6
0
        void CalculateCoinbase()
        {
            var reward = 1000u;

            var outputs = new List <Types.Output>
            {
                new Types.Output(Types.OutputLock.NewPKLock(_Address.Bytes), new Types.Spend(Tests.zhash, reward))
            };

            var witness = new List <byte[]>
            {
                BitConverter.GetBytes(_BlockChain.Tip.Value.header.blockNumber + 1)
            };

            _Coinbase = new Types.Transaction(
                0,
                ListModule.Empty <Types.Outpoint>(),
                ListModule.OfSeq(witness),
                ListModule.OfSeq(outputs),
                FSharpOption <Types.ExtendedContract> .None
                );
        }
示例#7
0
        public static Types.Transaction GetCoinbaseTx(uint blockNumber)
        {
            var reward = 1000u;

            var outputs = new List <Types.Output>
            {
                new Types.Output(Types.OutputLock.NewPKLock(Key.Create().Address.Bytes), new Types.Spend(Consensus.Tests.zhash, reward))
            };

            var witness = new List <byte[]>
            {
                BitConverter.GetBytes(blockNumber)
            };

            return(new Types.Transaction(
                       0,
                       ListModule.Empty <Types.Outpoint>(),
                       ListModule.OfSeq(witness),
                       ListModule.OfSeq(outputs),
                       FSharpOption <Types.ExtendedContract> .None
                       ));
        }
示例#8
0
        bool ExtendMain(List <QueueAction> queuedActions, double totalWork, bool isGenesis = false)
        {
            if (_BlockChain.BlockStore.ContainsKey(_DbTx, _BkHash))
            {
                _BlockChain.BlockStore.SetLocation(_DbTx, _BkHash, LocationEnum.Main);
            }
            else
            {
                _BlockChain.BlockStore.Put(_DbTx, _BkHash, _Bk, LocationEnum.Main, totalWork);
            }

            _BlockChain.Timestamps.Push(_Bk.header.timestamp);

            if (_Bk.header.blockNumber % 2000 == 0)
            {
                _BlockChain.BlockNumberDifficulties.Add(_DbTx.Transaction, _Bk.header.blockNumber, _BkHash);
            }

            var blockUndoData = new BlockUndoData();

            var confirmedTxs = new HashDictionary <TransactionValidation.PointedTransaction>();

            //TODO: lock with mempool
            for (var txIdx = 0; txIdx < _Bk.transactions.Count(); txIdx++)
            {
                var tx     = _Bk.transactions[txIdx];
                var txHash = Merkle.transactionHasher.Invoke(tx);
                TransactionValidation.PointedTransaction ptx;

                if (!isGenesis)
                {
                    if ((txIdx == 0 && !IsCoinbaseTxValid(tx)) || (txIdx > 0 && IsCoinbaseTxValid(tx)))
                    {
                        if (txIdx == 0)
                        {
                            BlockChainTrace.Information("Invalid coinbase tx");
                        }
                        else
                        {
                            BlockChainTrace.Information($"Invalid tx ({txIdx})");
                        }

                        return(false);
                    }

                    if (!IsTransactionValid(tx, txHash, out ptx))
                    {
                        return(false);
                    }

                    confirmedTxs[txHash] = ptx;

                    foreach (var pInput in ptx.pInputs)
                    {
                        _BlockChain.UTXOStore.Remove(_DbTx, pInput.Item1);
                        BlockChainTrace.Information($"utxo spent, amount {pInput.Item2.spend.amount}", ptx);
                        //BlockChainTrace.Information($" of", pInput.Item1.txHash);
                        blockUndoData.RemovedUTXO.Add(new Tuple <Types.Outpoint, Types.Output>(pInput.Item1, pInput.Item2));
                    }
                }
                else
                {
                    ptx = TransactionValidation.toPointedTransaction(
                        tx,
                        ListModule.Empty <Types.Output>()
                        );
                }

                _BlockChain.BlockStore.TxStore.Put(_DbTx, txHash, tx, true);

                var contractExtendSacrifices = new HashDictionary <ulong>();
                var activationSacrifice      = 0UL;

                for (var outputIdx = 0; outputIdx < tx.outputs.Count(); outputIdx++)
                {
                    var output = tx.outputs[outputIdx];

                    if ([email protected])
                    {
                        if (!output.spend.asset.SequenceEqual(Tests.zhash))
                        {
                            continue;                             // not Zen
                        }
                        var contractSacrificeLock = (Types.OutputLock.ContractSacrificeLock)output.@lock;

                        if (contractSacrificeLock.IsHighVLock)
                        {
                            continue;                             // not current version
                        }
                        if (contractSacrificeLock.Item.lockData.Length > 0 && contractSacrificeLock.Item.lockData[0] != null && contractSacrificeLock.Item.lockData[0].Length > 0)
                        {
                            var contractKey = contractSacrificeLock.Item.lockData[0];                             // output-lock-level indicated contract

                            contractExtendSacrifices[contractKey] =
                                (contractExtendSacrifices.ContainsKey(contractKey) ? contractExtendSacrifices[contractKey] : 0) +
                                output.spend.amount;
                        }
                        else if (contractSacrificeLock.Item.lockData.Length == 0)
                        {
                            activationSacrifice += output.spend.amount;
                        }
                    }

                    //todo: fix  to exclude CSLocks&FLocks, instead of including by locktype
                    if ([email protected] || [email protected])
                    {
                        BlockChainTrace.Information($"new utxo, amount {output.spend.amount}", tx);
                        var outpoint = new Types.Outpoint(txHash, (uint)outputIdx);
                        _BlockChain.UTXOStore.Put(_DbTx, outpoint, output);
                        blockUndoData.AddedUTXO.Add(new Tuple <Types.Outpoint, Types.Output>(outpoint, output));
                    }
                }

                if (FSharpOption <Types.ExtendedContract> .get_IsSome(tx.contract) && !tx.contract.Value.IsHighVContract)
                {
                    var codeBytes    = ((Types.ExtendedContract.Contract)tx.contract.Value).Item.code;
                    var contractHash = Merkle.innerHash(codeBytes);
                    var contractCode = System.Text.Encoding.ASCII.GetString(codeBytes);

                    if (_BlockChain.ActiveContractSet.TryActivate(_DbTx, contractCode, activationSacrifice, contractHash, _Bk.header.blockNumber))
                    {
                        blockUndoData.ACSDeltas.Add(contractHash, new ACSUndoData());
                        ContractsTxsStore.Add(_DbTx.Transaction, contractHash, txHash);
                    }
                }

                foreach (var item in contractExtendSacrifices)
                {
                    var currentACSItem = _BlockChain.ActiveContractSet.Get(_DbTx, item.Key);

                    if (currentACSItem.Value != null)
                    {
                        if (_BlockChain.ActiveContractSet.TryExtend(_DbTx, item.Key, item.Value))
                        {
                            if (!blockUndoData.ACSDeltas.ContainsKey(item.Key))
                            {
                                blockUndoData.ACSDeltas.Add(item.Key, new ACSUndoData()
                                {
                                    LastBlock = currentACSItem.Value.LastBlock
                                });
                            }
                        }
                    }
                }
            }

            var expiringContracts = _BlockChain.ActiveContractSet.GetExpiringList(_DbTx, _Bk.header.blockNumber);

            foreach (var acsItem in expiringContracts)
            {
                if (!blockUndoData.ACSDeltas.ContainsKey(acsItem.Key))
                {
                    blockUndoData.ACSDeltas.Add(acsItem.Key, new ACSUndoData()
                    {
                        ACSItem = acsItem.Value
                    });
                }
            }

            if (!isGenesis)
            {
                _BlockChain.BlockStore.SetUndoData(_DbTx, _BkHash, blockUndoData);
            }

            _BlockChain.ActiveContractSet.DeactivateContracts(_DbTx, expiringContracts.Select(t => t.Key));

            ValidateACS();

            _BlockChain.ChainTip.Context(_DbTx).Value = _BkHash;
            //TODO: only update after commit
            _BlockChain.Tip = new Keyed <Types.Block>(_BkHash, _Bk);

            queuedActions.Add(new MessageAction(new BlockMessage(confirmedTxs, _Bk.header.blockNumber)));

            foreach (var item in confirmedTxs)
            {
                ConfirmedTxs[item.Key] = item.Value;
                UnconfirmedTxs.Remove(item.Key);
            }

            return(true);
        }
示例#9
0
 public static Option <FSharpList <T> > FromSequence <T>(IEnumerable <Option <T> > sources) =>
 FromSequenceH(ListModule.OfSeq(sources.Reverse()), ListModule.Empty <T>());
示例#10
0
        void RecalculateHeader()
        {
            if (_BlockChain.Tip == null)
            {
                return;
            }

            if (_TransactionQueue.IsStuck)
            {
                MinerTrace.Information("Queue is stuck. count = " + _TransactionQueue.Count);
            }

            while (!_TransactionQueue.IsStuck && _ValidatedTxs.Count < TxsPerBlockLimit)
            {
                var ptx = _TransactionQueue.Take();

                if (IsTransactionValid(ptx))
                {
                    _ValidatedTxs.Add(ptx);

                    _TransactionQueue.Remove();

                    HandleTx(ptx);
                }
                else
                {
                    MinerTrace.Information("Tx invalid");
                    _TransactionQueue.Next();
                }
            }

            if (_ValidatedTxs.Count == 0)
            {
                MinerTrace.Information("No txs");
                return;                 // don't allow empty blocks
            }

            CalculateCoinbase();

            var txs = ListModule.OfSeq(FSharpList <Types.Transaction> .Cons(_Coinbase, ListModule.OfSeq(_ValidatedTxs.Select(TransactionValidation.unpoint))));

            _Header = new Types.BlockHeader(
                0,
                _BlockChain.Tip.Key,
                _BlockChain.Tip.Value.header.blockNumber + 1,
                Merkle.merkleRoot(
                    new byte[] { },
                    Merkle.transactionHasher,
                    txs
                    ),
                new byte[] { },
                new byte[] { },
                ListModule.Empty <byte[]>(),
                DateTime.Now.ToUniversalTime().Ticks,
                Difficulty,
                new byte[12]
                );

            MinerTrace.Information($"Mining block number {_BlockChain.Tip.Value.header.blockNumber + 1} with {_ValidatedTxs.Count()} txs");

            _Hasher.SetHeader(_Header);
            _Hasher.Continue();
        }
示例#11
0
        public override IEnumerable <Types.ItemLocation> GetItemLocations(int Seed)
        {
            var rnd = new Random(Seed);

            var NumSupers   = 11 + rnd.Next(7);
            var NumPBs      = 13 + rnd.Next(7);
            var NumMissiles = 63 - NumSupers - NumPBs;

            var ItemPool = Items.addReserves(3, Items.Items);

            ItemPool = Items.addETanks(13, ItemPool);
            ItemPool = Items.addMissiles(NumMissiles, ItemPool);
            ItemPool = Items.addSupers(NumSupers, ItemPool);
            ItemPool = Items.addPowerBombs(NumPBs, ItemPool);

            var NewItems      = ListModule.Empty <Types.Item> ();
            var ItemLocations = ListModule.Empty <Types.ItemLocation> ();

            // Place Morph at one of the earliest locations so that it's always accessible
            NewRandomizer.prefill(rnd, Types.ItemType.Morph, ref NewItems, ref ItemLocations,
                                  ref ItemPool, TournamentLocations.AllLocations);

            // Place either a super or a missile to open up BT's location
            var BT_Access = rnd.Next(100) < 65 ? Types.ItemType.Missile : Types.ItemType.Super;

            NewRandomizer.prefill(rnd, BT_Access, ref NewItems, ref ItemLocations,
                                  ref ItemPool, TournamentLocations.AllLocations);

            // Next step is to place items that opens up access to breaking bomb blocks
            // by placing either Screw/Speed/Bomb or just a PB pack early.
            // One PB pack will be placed after filling with other items so that there's at least one accessible
            Types.ItemType BombBreaker;
            switch (rnd.Next(13))
            {
            case 0:
                BombBreaker = Types.ItemType.SpeedBooster;
                break;

            case 1:
            case 2:
                BombBreaker = Types.ItemType.ScrewAttack;
                break;

            case 3:
            case 4:
            case 5:
            case 6:
                BombBreaker = Types.ItemType.Bomb;
                break;

            default:
                BombBreaker = Types.ItemType.PowerBomb;
                break;
            }
            NewRandomizer.prefill(rnd, BombBreaker, ref NewItems, ref ItemLocations,
                                  ref ItemPool, TournamentLocations.AllLocations);

            // Place a super if it's not already placed
            if (NewItems.Count(p => p.Type == Types.ItemType.Super) < 1)
            {
                NewRandomizer.prefill(rnd, Types.ItemType.Super, ref NewItems, ref ItemLocations,
                                      ref ItemPool, TournamentLocations.AllLocations);
            }

            // Place a power bomb if it's not already placed
            if (NewItems.Count(p => p.Type == Types.ItemType.PowerBomb) < 1)
            {
                NewRandomizer.prefill(rnd, Types.ItemType.PowerBomb, ref NewItems, ref ItemLocations,
                                      ref ItemPool, TournamentLocations.AllLocations);
            }

            return(NewRandomizer.generateItemsWithoutPrefill(rnd, NewItems,
                                                             ItemLocations, ItemPool, TournamentLocations.AllLocations));
        }