Пример #1
0
        public void TestBlockchainEquality()
        {
            var randomBlockchain = RandomData.RandomBlockchain();

            var sameBlockchain = new Blockchain
            (
                blockList: ImmutableList.Create(randomBlockchain.BlockList.ToArray()),
                blockListHashes: ImmutableHashSet.Create(randomBlockchain.BlockListHashes.ToArray()),
                utxo: randomBlockchain.Utxo.ToDictionary(x => x.Key, x => x.Value).ToImmutableDictionary(x => x.Key, x => x.Value)
            );

            var newChainedBlock = randomBlockchain.BlockList.Last();
            newChainedBlock = new ChainedBlock(newChainedBlock.BlockHash, newChainedBlock.PreviousBlockHash, newChainedBlock.Height + 1, newChainedBlock.TotalWork);
            var differentBlockchainBlockList = new Blockchain
            (
                blockList: randomBlockchain.BlockList.Add(newChainedBlock),
                blockListHashes: randomBlockchain.BlockListHashes,
                utxo: randomBlockchain.Utxo
            );

            var differentBlockchainBlockListHashes = new Blockchain
            (
                blockList: randomBlockchain.BlockList,
                blockListHashes: randomBlockchain.BlockListHashes.Remove(randomBlockchain.BlockListHashes.Last()),
                utxo: randomBlockchain.Utxo
            );

            var differentBlockchainUtxo = new Blockchain
            (
                blockList: randomBlockchain.BlockList,
                blockListHashes: randomBlockchain.BlockListHashes,
                utxo: randomBlockchain.Utxo.Remove(randomBlockchain.Utxo.Keys.Last())
            );

            Assert.IsTrue(randomBlockchain.Equals(sameBlockchain));
            Assert.IsTrue(randomBlockchain == sameBlockchain);
            Assert.IsFalse(randomBlockchain != sameBlockchain);

            Assert.IsFalse(randomBlockchain.Equals(differentBlockchainBlockList));
            Assert.IsFalse(randomBlockchain == differentBlockchainBlockList);
            Assert.IsTrue(randomBlockchain != differentBlockchainBlockList);

            Assert.IsFalse(randomBlockchain.Equals(differentBlockchainBlockListHashes));
            Assert.IsFalse(randomBlockchain == differentBlockchainBlockListHashes);
            Assert.IsTrue(randomBlockchain != differentBlockchainBlockListHashes);

            Assert.IsFalse(randomBlockchain.Equals(differentBlockchainUtxo));
            Assert.IsFalse(randomBlockchain == differentBlockchainUtxo);
            Assert.IsTrue(randomBlockchain != differentBlockchainUtxo);
        }
Пример #2
0
 public static Contract GetContract(object script_hash)
 {
     byte[] _script_hash = (byte[])script_hash;
     return(Blockchain.GetContract(_script_hash));
 }
Пример #3
0
        private static bool IsPayable(byte[] to)
        {
            var c = Blockchain.GetContract(to);

            return(c == null || c.IsPayable);
        }
Пример #4
0
        public static byte[] GetContract_Script(byte[] script_hash)
        {
            Contract cont = Blockchain.GetContract(script_hash);

            return(cont.Script);
        }
Пример #5
0
 public static Block GetBlock(object hash)
 {
     byte[] _hash = (byte[])hash;
     return(Blockchain.GetBlock(_hash));
 }
Пример #6
0
        protected internal override void OnStart(string[] args)
        {
            bool useRPC = false, nopeers = false, useLog = false;

            for (int i = 0; i < args.Length; i++)
            {
                switch (args[i])
                {
                case "/rpc":
                case "--rpc":
                case "-r":
                    useRPC = true;
                    break;

                case "--nopeers":
                    nopeers = true;
                    break;

                case "-l":
                case "--log":
                    useLog = true;
                    break;
                }
            }
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Path.GetFullPath(Settings.Default.Paths.Chain)));
            if (!nopeers && File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }
            LocalNode = new LocalNode();
            if (useLog)
            {
                LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
            }
            Task.Run(() =>
            {
                const string path_acc = "chain.acc";
                if (File.Exists(path_acc))
                {
                    using (FileStream fs = new FileStream(path_acc, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                }
                const string path_acc_zip = path_acc + ".zip";
                if (File.Exists(path_acc_zip))
                {
                    using (FileStream fs = new FileStream(path_acc_zip, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(path_acc).Open())
                            {
                                ImportBlocks(zs);
                            }
                }
                var paths = Directory.EnumerateFiles(".", "chain.*.acc", SearchOption.TopDirectoryOnly).Concat(Directory.EnumerateFiles(".", "chain.*.acc.zip", SearchOption.TopDirectoryOnly)).Select(p => new
                {
                    FileName     = Path.GetFileName(p),
                    Start        = uint.Parse(Regex.Match(p, @"\d+").Value),
                    IsCompressed = p.EndsWith(".zip")
                }).OrderBy(p => p.Start);
                foreach (var path in paths)
                {
                    if (path.Start > Blockchain.Default.Height + 1)
                    {
                        break;
                    }
                    if (path.IsCompressed)
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                            using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                                using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open())
                                {
                                    ImportBlocks(zs, true);
                                }
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.None))
                        {
                            ImportBlocks(fs, true);
                        }
                    }
                }
                LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
                if (Settings.Default.UnlockWallet.IsActive)
                {
                    try
                    {
                        Program.Wallet = OpenWallet(Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password);
                    }
                    catch (CryptographicException)
                    {
                        Console.WriteLine($"failed to open file \"{Settings.Default.UnlockWallet.Path}\"");
                    }
                    if (Settings.Default.UnlockWallet.StartConsensus && Program.Wallet != null)
                    {
                        OnStartConsensusCommand(null);
                    }
                }
                if (useRPC)
                {
                    rpc = new RpcServerWithWallet(LocalNode);
                    rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword);
                }
            });
        }
Пример #7
0
        public static byte[] GetTransaction_Hash(byte[] txid)
        {
            Transaction tran = Blockchain.GetTransaction(txid);

            return(tran.Hash);
        }
Пример #8
0
 public NeoEmulator()
 {
     this.blockchain = new Blockchain();
     this.emulator   = new Emulator(this.blockchain);
 }
Пример #9
0
        public static object HandleKYCOperation(string operation, params object[] args)
        {
            if (operation == "crowdsale_status")
            {
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(AddressIsWhitelisted((byte[])args[0]));
            }
            else if (operation == "GetGroupNumber")
            {
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(GetWhitelistGroupNumber((byte[])args[0]));
            }
            else if (operation == "GroupParticipationIsUnlocked")
            {
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(GroupParticipationIsUnlocked((int)args[0]));
            }
            else if (operation == "GetBlockHeight")
            {
                return(Blockchain.GetHeight());
            }

            switch (operation)
            {
            case "AddAddress":
                if (!Helpers.RequireArgumentLength(args, 2))
                {
                    return(false);
                }
                return(AddAddress((byte[])args[0], (int)args[1]));

            case "GetGroupMaxContribution":
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(GetGroupMaxContribution((BigInteger)args[0]));

            case "GetGroupUnlockBlock":
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(GetGroupUnlockBlock((BigInteger)args[0]));

            case "RevokeAddress":
                if (!Helpers.RequireArgumentLength(args, 1))
                {
                    return(false);
                }
                return(RevokeAddress((byte[])args[0]));

            case "SetGroupMaxContribution":
                if (!Helpers.RequireArgumentLength(args, 2))
                {
                    return(false);
                }
                return(SetGroupMaxContribution((BigInteger)args[0], (uint)args[1]));

            case "SetGroupUnlockBlock":
                if (!Helpers.RequireArgumentLength(args, 2))
                {
                    return(false);
                }
                return(SetGroupUnlockBlock((BigInteger)args[0], (uint)args[1]));
            }

            return(false);
        }
Пример #10
0
        public void BlockchainTest()
        {
            var b = new Blockchain();

            b.Chain.Last().Timestamp = 1562138682.8718169;

            // genesis block
            {
                var block = b.LastBlock;
                block.Index.Should().Be(1);
                block.Proof.Should().Be(100);
                block.PreviousHash.Should().Be("1");
                block.Transactions.Count.Should().Be(0);
            }

            // new transaction
            {
                var result = b.NewTransaction("8527147fe1f5426f9dd545de4b27ee00", "a77f5cdfa2934df3954a5c7c7da5df1f", 5);
                result.Should().Be(2);
            }

            // proof of work and new block
            {
                var proof        = Blockchain.ProofOfWork(b.LastBlock);
                var previousHash = Blockchain.Hash(b.LastBlock);
                proof.Should().Be(2964);
                previousHash.Should().Be("26aa6d44bd141589a0d3a1a90b86bf411de90d948abab3557b5b30ca75e4e904");

                var block = b.NewBlock(proof, previousHash);
                b.Chain.Last().Timestamp = 1562138730.8820634;
                block.Index.Should().Be(2);
                block.Proof.Should().Be(proof);
                block.PreviousHash.Should().Be(previousHash);

                var transactions = block.Transactions;
                transactions.Count.Should().Be(1);
                var transaction = transactions[0];
                transaction.Sender.Should().Be("8527147fe1f5426f9dd545de4b27ee00");
                transaction.Recipient.Should().Be("a77f5cdfa2934df3954a5c7c7da5df1f");
                transaction.Amount.Should().Be(5);
            }

            // new transactions
            {
                int result;
                result = b.NewTransaction("f5904ab1209feccb054a79783a508e66", "ad9be4f7f91188b5b3509efd7e9973fa", 42);
                result.Should().Be(3);
                result = b.NewTransaction("06246b36066a3f615ec81085c89cbefd", "16b539269e260e2cce7bf9a1d666c78e", 13);
                result.Should().Be(3);
            }

            // proof of work and new block
            {
                var proof        = Blockchain.ProofOfWork(b.LastBlock);
                var previousHash = Blockchain.Hash(b.LastBlock);
                proof.Should().Be(2409);
                previousHash.Should().Be("7ef1a64eec40e553f39acc252bb3444100d6a95f305e74c2fc40d41d86bbc1d4");

                var block = b.NewBlock(proof, previousHash);
                b.Chain.Last().Timestamp = 1562138771.2577565;
                block.Index.Should().Be(3);
                block.Proof.Should().Be(proof);
                block.PreviousHash.Should().Be(previousHash);

                var transactions = block.Transactions;
                transactions.Count.Should().Be(2);
                Transaction transaction;
                transaction = transactions[0];
                transaction.Sender.Should().Be("f5904ab1209feccb054a79783a508e66");
                transaction.Recipient.Should().Be("ad9be4f7f91188b5b3509efd7e9973fa");
                transaction.Amount.Should().Be(42);
                transaction = transactions[1];
                transaction.Sender.Should().Be("06246b36066a3f615ec81085c89cbefd");
                transaction.Recipient.Should().Be("16b539269e260e2cce7bf9a1d666c78e");
                transaction.Amount.Should().Be(13);
            }

            // proof of work
            {
                var proof        = Blockchain.ProofOfWork(b.LastBlock);
                var previousHash = Blockchain.Hash(b.LastBlock);
                proof.Should().Be(28486);
                previousHash.Should().Be("2d095dd4fb79711fdb3e780f5ae6ddab1190ddfaa170ee1a1dcb2425bd645652");
            }
        }
Пример #11
0
 public QuestionResultQuery(Blockchain blockchain)
 {
     this.blockchain = blockchain;
 }
Пример #12
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbl_height.Text     = $"{Blockchain.Default.Height}/{Blockchain.Default.HeaderHeight}";
            lbl_count_node.Text = Program.LocalNode.RemoteNodeCount.ToString();
            TimeSpan persistence_span = DateTime.Now - persistence_time;

            if (persistence_span > Blockchain.TimePerBlock)
            {
                toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
            }
            else
            {
                toolStripProgressBar1.Value = persistence_span.Seconds;
                toolStripProgressBar1.Style = ProgressBarStyle.Blocks;
            }
            if (Program.CurrentWallet?.WalletHeight > Blockchain.Default.Height + 1)
            {
                return;
            }
            if (balance_changed)
            {
                IEnumerable <Coin> coins             = Program.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                Fixed8             bonus_available   = Blockchain.CalculateBonus(Program.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                Fixed8             bonus_unavailable = Blockchain.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.SystemShare.Hash)).Select(p => p.Reference), Blockchain.Default.Height + 1);
                Fixed8             bonus             = bonus_available + bonus_unavailable;
                var assets = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                {
                    Asset = Blockchain.Default.GetAssetState(k),
                    Value = g.Sum(p => p.Output.Value),
                    Claim = k.Equals(Blockchain.SystemCoin.Hash) ? bonus : Fixed8.Zero
                }).ToDictionary(p => p.Asset.AssetId);
                if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.SystemCoin.Hash))
                {
                    assets[Blockchain.SystemCoin.Hash] = new
                    {
                        Asset = Blockchain.Default.GetAssetState(Blockchain.SystemCoin.Hash),
                        Value = Fixed8.Zero,
                        Claim = bonus
                    };
                }
                var balance_ans = coins.Where(p => p.Output.AssetId.Equals(Blockchain.SystemShare.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                var balance_anc = coins.Where(p => p.Output.AssetId.Equals(Blockchain.SystemCoin.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                foreach (ListViewItem item in listView1.Items)
                {
                    UInt160 script_hash = Wallet.ToScriptHash(item.Name);
                    Fixed8  ans         = balance_ans.ContainsKey(script_hash) ? balance_ans[script_hash] : Fixed8.Zero;
                    Fixed8  anc         = balance_anc.ContainsKey(script_hash) ? balance_anc[script_hash] : Fixed8.Zero;
                    item.SubItems["ans"].Text = ans.ToString();
                    item.SubItems["anc"].Text = anc.ToString();
                }
                foreach (AssetState asset in listView2.Items.OfType <ListViewItem>().Select(p => (AssetState)p.Tag).ToArray())
                {
                    if (!assets.ContainsKey(asset.AssetId))
                    {
                        listView2.Items.RemoveByKey(asset.AssetId.ToString());
                    }
                }
                foreach (var asset in assets.Values)
                {
                    string value_text = asset.Value.ToString() + (asset.Asset.AssetId.Equals(Blockchain.SystemCoin.Hash) ? $"+({asset.Claim})" : "");
                    if (listView2.Items.ContainsKey(asset.Asset.AssetId.ToString()))
                    {
                        listView2.Items[asset.Asset.AssetId.ToString()].SubItems["value"].Text = value_text;
                    }
                    else
                    {
                        listView2.Items.Add(new ListViewItem(new[]
                        {
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "name",
                                Text = asset.Asset.GetName()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "type",
                                Text = asset.Asset.AssetType.ToString()
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                Name = "value",
                                Text = value_text
                            },
                            new ListViewItem.ListViewSubItem
                            {
                                ForeColor = Color.Gray,
                                Name      = "issuer",
                                Text      = $"{Strings.UnknownIssuer}[{asset.Asset.Owner}]"
                            }
                        }, -1, listView2.Groups["unchecked"])
                        {
                            Name = asset.Asset.AssetId.ToString(),
                            Tag  = asset.Asset,
                            UseItemStyleForSubItems = false
                        });
                    }
                }
                balance_changed = false;
            }
            foreach (ListViewItem item in listView2.Groups["unchecked"].Items.OfType <ListViewItem>().ToArray())
            {
                ListViewItem.ListViewSubItem subitem = item.SubItems["issuer"];
                AssetState             asset         = (AssetState)item.Tag;
                CertificateQueryResult result;
                if (asset.AssetType == AssetType.SystemShare || asset.AssetType == AssetType.SystemCoin)
                {
                    result = new CertificateQueryResult {
                        Type = CertificateQueryResultType.System
                    };
                }
                else
                {
                    result = CertificateQueryService.Query(asset.Owner);
                }
                using (result)
                {
                    subitem.Tag = result.Type;
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.Querying:
                    case CertificateQueryResultType.QueryFailed:
                        break;

                    case CertificateQueryResultType.System:
                        subitem.ForeColor = Color.Green;
                        subitem.Text      = Strings.SystemIssuer;
                        break;

                    case CertificateQueryResultType.Invalid:
                        subitem.ForeColor = Color.Red;
                        subitem.Text      = $"[{Strings.InvalidCertificate}][{asset.Owner}]";
                        break;

                    case CertificateQueryResultType.Expired:
                        subitem.ForeColor = Color.Yellow;
                        subitem.Text      = $"[{Strings.ExpiredCertificate}]{result.Certificate.Subject}[{asset.Owner}]";
                        break;

                    case CertificateQueryResultType.Good:
                        subitem.ForeColor = Color.Black;
                        subitem.Text      = $"{result.Certificate.Subject}[{asset.Owner}]";
                        break;
                    }
                    switch (result.Type)
                    {
                    case CertificateQueryResultType.System:
                    case CertificateQueryResultType.Missing:
                    case CertificateQueryResultType.Invalid:
                    case CertificateQueryResultType.Expired:
                    case CertificateQueryResultType.Good:
                        item.Group = listView2.Groups["checked"];
                        break;
                    }
                }
            }
        }
Пример #13
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            lbl_height.Text    = $"{StringTable.DATA[iLang, 33]} : {Constant.CurrentWallet.WalletHeight - 1}/{Blockchain.Default.Height}/{Blockchain.Default.HeaderHeight}";
            lbl_connected.Text = $"{StringTable.DATA[iLang, 34]} : " + Constant.LocalNode.RemoteNodeCount.ToString();

            if (Constant.CurrentWallet != null)
            {
                if (Constant.CurrentWallet.WalletHeight <= Blockchain.Default.Height + 1)
                {
                    if (balance_changed)
                    {
                        IEnumerable <Coin>   coins   = Constant.CurrentWallet?.GetCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <Coin>();
                        IEnumerable <JSCoin> jscoins = Constant.CurrentWallet?.GetJSCoins().Where(p => !p.State.HasFlag(CoinState.Spent)) ?? Enumerable.Empty <JSCoin>();

                        Fixed8 bonus_available   = Blockchain.CalculateBonus(Constant.CurrentWallet.GetUnclaimedCoins().Select(p => p.Reference));
                        Fixed8 bonus_unavailable = Blockchain.CalculateBonus(coins.Where(p => p.State.HasFlag(CoinState.Confirmed) && p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).Select(p => p.Reference), Blockchain.Default.Height + 1);
                        Fixed8 bonus             = bonus_available + bonus_unavailable;
                        var    assets            = coins.GroupBy(p => p.Output.AssetId, (k, g) => new
                        {
                            Asset = Blockchain.Default.GetAssetState(k),
                            Value = g.Sum(p => p.Output.Value),
                            Claim = k.Equals(Blockchain.UtilityToken.Hash) ? bonus : Fixed8.Zero
                        }).ToDictionary(p => p.Asset.AssetId);
                        if (bonus != Fixed8.Zero && !assets.ContainsKey(Blockchain.UtilityToken.Hash))
                        {
                            assets[Blockchain.UtilityToken.Hash] = new
                            {
                                Asset = Blockchain.Default.GetAssetState(Blockchain.UtilityToken.Hash),
                                Value = Fixed8.Zero,
                                Claim = bonus
                            };
                        }
                        var    balance_qrs    = coins.Where(p => p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        var    balance_js_qrs = jscoins.Where(p => p.Output.AssetId.Equals(Blockchain.GoverningToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        var    balance_qrg    = coins.Where(p => p.Output.AssetId.Equals(Blockchain.UtilityToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        var    balance_js_qrg = jscoins.Where(p => p.Output.AssetId.Equals(Blockchain.UtilityToken.Hash)).GroupBy(p => p.Output.ScriptHash).ToDictionary(p => p.Key, p => p.Sum(i => i.Output.Value));
                        Fixed8 qrs_total      = Fixed8.Zero;
                        Fixed8 qrg_total      = Fixed8.Zero;
                        foreach (UInt160 scriptHash in Constant.CurrentWallet.GetAddresses().ToArray())
                        {
                            VerificationContract contract = Constant.CurrentWallet.GetContract(scriptHash);

                            Fixed8 qrs    = balance_qrs.ContainsKey(scriptHash) ? balance_qrs[scriptHash] : Fixed8.Zero;
                            Fixed8 js_qrs = balance_js_qrs.ContainsKey(scriptHash) ? balance_js_qrs[scriptHash] : Fixed8.Zero;
                            Fixed8 qrg    = balance_qrg.ContainsKey(scriptHash) ? balance_qrg[scriptHash] : Fixed8.Zero;
                            Fixed8 js_qrg = balance_js_qrg.ContainsKey(scriptHash) ? balance_js_qrg[scriptHash] : Fixed8.Zero;

                            AddressAssetsImp.getInstance().RefrshAssets(contract.Address, Blockchain.GoverningToken.Hash, (qrs + js_qrs).ToString());
                            AddressAssetsImp.getInstance().RefrshAssets(contract.Address, Blockchain.UtilityToken.Hash, (qrg + js_qrg).ToString());

                            qrs_total += qrs;
                            qrs_total += js_qrs;
                            qrg_total += qrg;
                            qrg_total += js_qrg;
                        }

                        dashboardPan1.SetQRSTotalBalance(Helper.FormatNumber(qrs_total.ToString()));
                        dashboardPan1.SetQRGTotalBalance(Helper.FormatNumber(qrg_total.ToString()));

                        balance_changed = false;
                    }
                }
            }
        }
Пример #14
0
 public void Reset(byte viewNumber)
 {
     if (viewNumber == 0)
     {
         Snapshot?.Dispose();
         Snapshot = Blockchain.Singleton.GetSnapshot();
         Block    = new Block
         {
             PrevHash      = Snapshot.CurrentBlockHash,
             Index         = Snapshot.Height + 1,
             NextConsensus = Blockchain.GetConsensusAddress(NativeContract.NEO.GetValidators(Snapshot).ToArray())
         };
         var pv = Validators;
         Validators = NativeContract.NEO.GetNextBlockValidators(Snapshot);
         if (_witnessSize == 0 || (pv != null && pv.Length != Validators.Length))
         {
             // Compute the expected size of the witness
             using (ScriptBuilder sb = new ScriptBuilder())
             {
                 for (int x = 0; x < M; x++)
                 {
                     sb.EmitPush(new byte[64]);
                 }
                 _witnessSize = new Witness
                 {
                     InvocationScript   = sb.ToArray(),
                     VerificationScript = Contract.CreateMultiSigRedeemScript(M, Validators)
                 }.Size;
             }
         }
         MyIndex                = -1;
         ChangeViewPayloads     = new ConsensusPayload[Validators.Length];
         LastChangeViewPayloads = new ConsensusPayload[Validators.Length];
         CommitPayloads         = new ConsensusPayload[Validators.Length];
         if (LastSeenMessage == null)
         {
             LastSeenMessage = new int[Validators.Length];
             for (int i = 0; i < Validators.Length; i++)
             {
                 LastSeenMessage[i] = -1;
             }
         }
         keyPair = null;
         for (int i = 0; i < Validators.Length; i++)
         {
             WalletAccount account = wallet?.GetAccount(Validators[i]);
             if (account?.HasKey != true)
             {
                 continue;
             }
             MyIndex = i;
             keyPair = account.GetKey();
             break;
         }
     }
     else
     {
         for (int i = 0; i < LastChangeViewPayloads.Length; i++)
         {
             if (ChangeViewPayloads[i]?.GetDeserializedMessage <ChangeView>().NewViewNumber >= viewNumber)
             {
                 LastChangeViewPayloads[i] = ChangeViewPayloads[i];
             }
             else
             {
                 LastChangeViewPayloads[i] = null;
             }
         }
     }
     ViewNumber          = viewNumber;
     Block.ConsensusData = new ConsensusData
     {
         PrimaryIndex = GetPrimaryIndex(viewNumber)
     };
     Block.MerkleRoot    = null;
     Block.Timestamp     = 0;
     Block.Transactions  = null;
     TransactionHashes   = null;
     PreparationPayloads = new ConsensusPayload[Validators.Length];
     if (MyIndex >= 0)
     {
         LastSeenMessage[MyIndex] = (int)Block.Index;
     }
 }
Пример #15
0
        public void Check_BalanceOfTransferAndBurn()
        {
            var snapshot        = _snapshot.Clone();
            var persistingBlock = new Block()
            {
                Index = 1000
            };

            byte[] from     = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators).ToArray();
            byte[] to       = new byte[20];
            var    keyCount = snapshot.Storages.GetChangeSet().Count();
            var    supply   = NativeContract.GAS.TotalSupply(snapshot);

            supply.Should().Be(3000000050000000); // 3000000000000000 + 50000000 (neo holder reward)

            // Check unclaim

            var unclaim = UT_NeoToken.Check_UnclaimedGas(snapshot, from, persistingBlock);

            unclaim.Value.Should().Be(new BigInteger(0.5 * 1000 * 100000000L));
            unclaim.State.Should().BeTrue();

            // Transfer

            NativeContract.NEO.Transfer(snapshot, from, to, BigInteger.Zero, true, persistingBlock).Should().BeTrue();
            NativeContract.NEO.BalanceOf(snapshot, from).Should().Be(100000000);
            NativeContract.NEO.BalanceOf(snapshot, to).Should().Be(0);

            NativeContract.GAS.BalanceOf(snapshot, from).Should().Be(30000500_00000000);
            NativeContract.GAS.BalanceOf(snapshot, to).Should().Be(0);

            // Check unclaim

            unclaim = UT_NeoToken.Check_UnclaimedGas(snapshot, from, persistingBlock);
            unclaim.Value.Should().Be(new BigInteger(0));
            unclaim.State.Should().BeTrue();

            supply = NativeContract.GAS.TotalSupply(snapshot);
            supply.Should().Be(3000050050000000);

            snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount + 3); // Gas

            // Transfer

            keyCount = snapshot.Storages.GetChangeSet().Count();

            NativeContract.GAS.Transfer(snapshot, from, to, 30000500_00000000, false, persistingBlock).Should().BeFalse(); // Not signed
            NativeContract.GAS.Transfer(snapshot, from, to, 30000500_00000001, true, persistingBlock).Should().BeFalse();  // More than balance
            NativeContract.GAS.Transfer(snapshot, from, to, 30000500_00000000, true, persistingBlock).Should().BeTrue();   // All balance

            // Balance of

            NativeContract.GAS.BalanceOf(snapshot, to).Should().Be(30000500_00000000);
            NativeContract.GAS.BalanceOf(snapshot, from).Should().Be(0);

            snapshot.Storages.GetChangeSet().Count().Should().Be(keyCount + 1); // All

            // Burn

            var engine = ApplicationEngine.Create(TriggerType.Application, null, snapshot, persistingBlock, 0);

            keyCount = snapshot.Storages.GetChangeSet().Count();

            Assert.ThrowsException <ArgumentOutOfRangeException>(() =>
                                                                 NativeContract.GAS.Burn(engine, new UInt160(to), BigInteger.MinusOne));

            // Burn more than expected

            Assert.ThrowsException <InvalidOperationException>(() =>
                                                               NativeContract.GAS.Burn(engine, new UInt160(to), new BigInteger(30000500_00000001)));

            // Real burn

            NativeContract.GAS.Burn(engine, new UInt160(to), new BigInteger(1));

            NativeContract.GAS.BalanceOf(snapshot, to).Should().Be(3000049999999999);

            keyCount.Should().Be(snapshot.Storages.GetChangeSet().Count());

            // Burn all

            NativeContract.GAS.Burn(engine, new UInt160(to), new BigInteger(3000049999999999));

            (keyCount - 1).Should().Be(snapshot.Storages.GetChangeSet().Count());

            // Bad inputs

            NativeContract.GAS.Transfer(snapshot, from, to, BigInteger.MinusOne, true, persistingBlock).Should().BeFalse();
            NativeContract.GAS.Transfer(snapshot, new byte[19], to, BigInteger.One, false, persistingBlock).Should().BeFalse();
            NativeContract.GAS.Transfer(snapshot, from, new byte[19], BigInteger.One, false, persistingBlock).Should().BeFalse();
        }
Пример #16
0
        public static Object Main(string operation, params object[] args)
        {
            var magicstr = "2018-11-23 14:45";

            if (Runtime.Trigger == TriggerType.Verification)
            {
                return(false);
            }
            else if (Runtime.Trigger == TriggerType.Application)
            {
                var callscript = ExecutionEngine.CallingScriptHash;

                if (operation == "getSAR4B")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    byte[] addr = (byte[])args[0];
                    return(getSAR4B(addr));
                }
                if (operation == "openSAR4B")
                {
                    if (args.Length != 5)
                    {
                        return(false);
                    }
                    string name     = (string)args[0];
                    string symbol   = (string)args[1];
                    byte   decimals = (byte)args[2];
                    byte[] addr     = (byte[])args[3];
                    string anchor   = (string)args[4];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(openSAR4B(name, symbol, decimals, addr, anchor));
                }

                /**An example of upgrade 'accept' method, the createSARBC interface should been
                 *  implemented in the following new SARBC contract
                 */
                if (operation == "createSAR4B")
                {
                    if (args.Length != 9)
                    {
                        return(false);
                    }
                    byte[]     addr      = (byte[])args[0];
                    byte[]     txid      = (byte[])args[1];
                    string     name      = (string)args[2];
                    string     symbol    = (string)args[3];
                    byte       decimals  = (byte)args[4];
                    BigInteger locked    = (BigInteger)args[5];
                    BigInteger hasDrawed = (BigInteger)args[6];
                    int        status    = (int)args[7];
                    string     anchor    = (string)args[8];

                    SARInfo sar = new SARInfo();
                    sar.symbol    = symbol;
                    sar.anchor    = anchor;
                    sar.name      = name;
                    sar.decimals  = decimals;
                    sar.locked    = locked;
                    sar.hasDrawed = hasDrawed;
                    sar.owner     = addr;
                    sar.status    = status;
                    sar.txid      = txid;

                    byte[] account = Storage.Get(Storage.CurrentContext, getAccountKey(STORAGE_ACCOUNT_OLD.AsByteArray()));
                    if (account.AsBigInteger() != callscript.AsBigInteger())
                    {
                        return(false);
                    }

                    return(createSAR4B(addr, sar));
                }
                //Migrate SAR account to new contract by owner of SAR
                if (operation == "migrateSAR4B")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    byte[] addr = (byte[])args[0];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(migrateSAR4B(addr));
                }

                if (operation == "initToken")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    byte[] addr = (byte[])args[0];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(initToken(addr));
                }

                //lock SDS to SAR as collateral
                if (operation == "reserve")
                {
                    if (args.Length != 3)
                    {
                        return(false);
                    }
                    string     name  = (string)args[0];
                    byte[]     addr  = (byte[])args[1];
                    BigInteger value = (BigInteger)args[2];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(reserve(name, addr, value));
                }
                //issue stablecoin
                if (operation == "expande")
                {
                    if (args.Length != 3)
                    {
                        return(false);
                    }
                    string     name  = (string)args[0];
                    byte[]     addr  = (byte[])args[1];
                    BigInteger value = (BigInteger)args[2];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(expande(name, addr, value));
                }
                //payback stablecoin
                if (operation == "contract")
                {
                    if (args.Length != 3)
                    {
                        return(false);
                    }
                    string     name  = (string)args[0];
                    byte[]     addr  = (byte[])args[1];
                    BigInteger value = (BigInteger)args[2];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(contract(name, addr, value));
                }
                //get SDS from SAR
                if (operation == "withdraw")
                {
                    if (args.Length != 3)
                    {
                        return(false);
                    }
                    string     name  = (string)args[0];
                    byte[]     addr  = (byte[])args[1];
                    BigInteger value = (BigInteger)args[2];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(withdraw(name, addr, value));
                }

                if (operation == "claimRedeem")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    byte[] addr = (byte[])args[0];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(claimRedeem(addr));
                }

                if (operation == "setAccount")
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    string key     = (string)args[0];
                    byte[] address = (byte[])args[1];
                    //only committee account
                    if (!checkAdmin())
                    {
                        return(false);
                    }
                    return(setAccount(key, address));
                }
                //stablecoin holder can redeem locked SDS if this SAR is unsafe
                if (operation == "redeem")
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    byte[] addr    = (byte[])args[0];
                    byte[] sarAddr = (byte[])args[1];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(redeem(addr, sarAddr));
                }

                if (operation == "settingSAR")
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    string name = (string)args[0];
                    byte[] addr = (byte[])args[1];
                    //only committee account
                    if (!checkAdmin())
                    {
                        return(false);
                    }
                    return(settingSAR(name, addr));
                }

                if (operation == "setConfig")
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    string     key   = (string)args[0];
                    BigInteger value = (BigInteger)args[1];
                    //only committee account
                    if (!checkAdmin())
                    {
                        return(false);
                    }
                    return(setConfig(key, value));
                }

                if (operation == "destory")
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    string name = (string)args[0];
                    byte[] addr = (byte[])args[1];

                    if (!Runtime.CheckWitness(addr))
                    {
                        return(false);
                    }
                    return(destory(name, addr));
                }

                if (operation == "getConfig")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    string key = (string)args[0];

                    return(getConfig(key));
                }

                if (operation == "getSARTxInfo")
                {
                    if (args.Length != 1)
                    {
                        return(false);
                    }
                    byte[] txid = (byte[])args[0];
                    return(getSARTxInfo(txid));
                }
                #region contract upgrade
                if (operation == "upgrade")
                {
                    //only committee account
                    if (!checkAdmin())
                    {
                        return(false);
                    }

                    if (args.Length != 1 && args.Length != 9)
                    {
                        return(false);
                    }

                    byte[] script     = Blockchain.GetContract(ExecutionEngine.ExecutingScriptHash).Script;
                    byte[] new_script = (byte[])args[0];

                    if (script == new_script)
                    {
                        return(false);
                    }

                    byte[] parameter_list = new byte[] { 0x07, 0x10 };
                    byte   return_type    = 0x05;
                    //1|2|4
                    bool   need_storage = (bool)(object)07;
                    string name         = "business";
                    string version      = "1";
                    string author       = "alchemint";
                    string email        = "0";
                    string description  = "alchemint";

                    if (args.Length == 9)
                    {
                        parameter_list = (byte[])args[1];
                        return_type    = (byte)args[2];
                        need_storage   = (bool)args[3];
                        name           = (string)args[4];
                        version        = (string)args[5];
                        author         = (string)args[6];
                        email          = (string)args[7];
                        description    = (string)args[8];
                    }
                    Contract.Migrate(new_script, parameter_list, return_type, need_storage, name, version, author, email, description);
                    return(true);
                }
                #endregion
            }
            return(true);
        }
        //static int CheckRegister(byte[] callscript, byte[] p0, byte[] p1)
        //{

        //}
        public static object Main(string method, object[] args)
        {
            if (Runtime.Trigger == TriggerType.Verification)//取钱才会涉及这里
            {
                return(false);
            }
            else if (Runtime.Trigger == TriggerType.VerificationR)
            {
                return(false);
            }
            else if (Runtime.Trigger == TriggerType.Application)
            {
                string magic = "20180820";
                //必须在入口函数取得callscript,调用脚本的函数,也会导致执行栈变化,再取callscript就晚了
                var callscript = ExecutionEngine.CallingScriptHash;


                #region 通用功能,不需要权限验证
                if (method == "name")
                {
                    return("NNS DomainCenter");
                }
                if (method == "getDomain")
                {
                    var hash = (byte[])args[0];
                    return(getDomain(hash));
                }
                if (method == "getOwnerInfo")
                {
                    return(getOwnerInfo((byte[])args[0]));
                }
                //if (method == "getNameInfo")
                //{
                //    return getNameInfo((byte[])args[0]);
                //}
                if (method == "nameHash")
                {
                    var name = (string)args[0];
                    return(nameHash(name));
                }
                if (method == "nameHashSub")
                {
                    var rootHash  = (byte[])args[0];
                    var subdomain = (string)args[1];
                    return(nameHashSub(rootHash, subdomain));
                }
                if (method == "nameHashArray")
                {
                    string[] list = (string[])args[0];
                    return(nameHashArray(list));
                }
                if (method == "resolve")
                {
                    string protocol  = (string)args[0];
                    var    rootHash  = (byte[])args[1];
                    var    subdomain = (string)args[2];
                    return(resolve(protocol, rootHash, subdomain));
                }
                if (method == "resolveFull")
                {
                    string   protocol = (string)args[0];
                    string[] list     = (string[])args[0];
                    return(resolveFull(protocol, list));
                }
                #endregion
                #region 配置根合约注册器,仅限管理员
                if (method == "initRoot")
                {
                    if (Runtime.CheckWitness(superAdmin))
                    {
                        string rootdomain = (string)args[0];
                        byte[] register   = (byte[])args[1];
                        return(initRoot(rootdomain, register));
                    }
                    return(new byte[] { 0x00 });
                }
                #endregion
                #region 升级合约,耗费490,仅限管理员
                if (method == "upgrade")
                {
                    //不是管理员 不能操作
                    if (!Runtime.CheckWitness(superAdmin))
                    {
                        return(false);
                    }

                    if (args.Length != 1 && args.Length != 9)
                    {
                        return(false);
                    }

                    byte[] script     = Blockchain.GetContract(ExecutionEngine.ExecutingScriptHash).Script;
                    byte[] new_script = (byte[])args[0];
                    //如果传入的脚本一样 不继续操作
                    if (script == new_script)
                    {
                        return(false);
                    }

                    byte[] parameter_list = new byte[] { 0x07, 0x10 };
                    byte   return_type    = 0x05;
                    bool   need_storage   = (bool)(object)01;
                    string name           = "domaincenter";
                    string version        = "1";
                    string author         = "NEL";
                    string email          = "0";
                    string description    = "域名中心";

                    if (args.Length == 9)
                    {
                        parameter_list = (byte[])args[1];
                        return_type    = (byte)args[2];
                        need_storage   = (bool)args[3];
                        name           = (string)args[4];
                        version        = (string)args[5];
                        author         = (string)args[6];
                        email          = (string)args[7];
                        description    = (string)args[8];
                    }
                    Contract.Migrate(new_script, parameter_list, return_type, need_storage, name, version, author, email, description);
                    return(true);
                }
                #endregion
                #region 所有者接口 直接调用&智能合约
                if (method == "owner_SetOwner")
                {
                    int n = CheckOwner(callscript, (byte[])args[0], (byte[])args[1], (byte[])args[2]);
                    if (n == 1 || n == 2)
                    {
                        return(owner_SetOwner((byte[])args[1], (byte[])args[2]));
                    }
                    if (n == 3 || n == 4)
                    {
                        return(owner_SetOwner((byte[])args[2], (byte[])args[3]));
                    }
                    return(new byte[] { 0x00 });
                }
                if (method == "owner_SetRegister")
                {
                    int n = CheckOwner(callscript, (byte[])args[0], (byte[])args[1], (byte[])args[2]);
                    if (n == 1 || n == 2)
                    {
                        return(owner_SetRegister((byte[])args[1], (byte[])args[2]));
                    }
                    if (n == 3 || n == 4)
                    {
                        return(owner_SetRegister((byte[])args[2], (byte[])args[3]));
                    }
                    return(new byte[] { 0x00 });
                }
                if (method == "owner_SetResolver")
                {
                    int n = CheckOwner(callscript, (byte[])args[0], (byte[])args[1], (byte[])args[2]);
                    if (n == 1 || n == 2)
                    {
                        return(owner_SetResolver((byte[])args[1], (byte[])args[2]));
                    }
                    if (n == 3 || n == 4)
                    {
                        return(owner_SetResolver((byte[])args[2], (byte[])args[3]));
                    }
                    return(new byte[] { 0x00 });
                }
                #endregion
                #region 注册器接口 仅智能合约
                if (method == "register_SetSubdomainOwner")
                {
                    if (callscript.AsBigInteger() == jumpContract.AsBigInteger())
                    {//如果是跳板合约调用
                        byte[] _callscript = (byte[])args[0];
                        byte[] nnshash     = (byte[])args[1];
                        var    pinfo       = getOwnerInfo(nnshash);
                        //var register = Storage.Get(Storage.CurrentContext, nnshash.Concat(new byte[] { 0x01 }));
                        if (_callscript.AsBigInteger() == pinfo.register.AsBigInteger())
                        {
                            return(register_SetSubdomainOwner((byte[])args[1], (string)args[2], (byte[])args[3], ((byte[])args[4]).AsBigInteger(), pinfo));
                        }
                    }
                    else
                    {
                        byte[] nnshash = (byte[])args[0];
                        var    pinfo   = getOwnerInfo(nnshash);
                        //var register = Storage.Get(Storage.CurrentContext, nnshash.Concat(new byte[] { 0x01 }));
                        if (callscript.AsBigInteger() == pinfo.register.AsBigInteger())
                        {
                            return(register_SetSubdomainOwner((byte[])args[0], (string)args[1], (byte[])args[2], ((byte[])args[3]).AsBigInteger(), pinfo));
                        }
                    }
                    return(new byte[] { 0x00 });
                }
                #endregion
            }
            return(new byte[] { 0 });
        }
Пример #18
0
        public static void SetupTestBlockchain(UInt256 assetId)
        {
            Blockchain testBlockchain = new TestBlockchain(assetId);

            Blockchain.RegisterBlockchain(testBlockchain);
        }
Пример #19
0
        public static byte GetTransaction_Type(byte[] txid)
        {
            Transaction tran = Blockchain.GetTransaction(txid);

            return(tran.Type);
        }
Пример #20
0
 public FiscalsQuery(Blockchain blockchain)
 {
     this.blockchain = blockchain;
 }
Пример #21
0
        public static StorageContext GetContract_StorageContext(byte[] script_hash)
        {
            Contract cont = Blockchain.GetContract(script_hash);

            return(cont.StorageContext);
        }
Пример #22
0
        public IActionResult GetBlockchain()
        {
            Blockchain blockchain = MockedBlockchainService.Blockchain;

            return(Ok(blockchain.Blocks));
        }
Пример #23
0
 public static uint GetHeight()
 {
     return(Blockchain.GetHeight());
 }
Пример #24
0
        static void Main(string[] args)
        {
            #region Configs.

            BlockchainStorageManagerParameters managerParameters = new BlockchainStorageManagerParameters()
            {
                BlocksInUnit = 2
            };
            UnitRepositoryParameters repositoryParameters = new UnitRepositoryParameters()
            {
                DirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "blockchain")
            };
            WalletManagerParameters walletManagerParameters = new WalletManagerParameters()
            {
                WalletDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), "wallets")
            };

            NetworkParameters networkParametersFirst = new NetworkParameters()
            {
                AddressBookPath = Path.Combine(Directory.GetCurrentDirectory(), AddressBookPath),

                PeerHostName = Dns.GetHostName(),
                PeerPort     = 8910,

                ClientTimeout = new TimeSpan(0, 0, 4),
                ServerTimeout = new TimeSpan(0, 0, 4)
            };

            BasicMiningFactoryParameters parameters = new BasicMiningFactoryParameters()
            {
                HashLeastUpFactor = 1.25,
                HashMostUpFactor  = 1.75,

                HashLeastDownFactor = 0.25,
                HashMostDownFactor  = 0.75,

                DifficultyLeastUpFactor = 1.25,
                DifficultyMostUpFactor  = 1.75,

                DifficultyLeastDownFactor = 0.25,
                DifficultyMostDownFactor  = 0.75,

                MinDifficulty = Difficulty
            };

            JsonSerializer jsonSerializer = new JsonSerializer()
            {
                Formatting = Formatting.Indented
            };

            using (Stream jsonFile = File.Open(MiningConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, parameters);

            using (Stream jsonFile = File.Open(ManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, managerParameters);

            using (Stream jsonFile = File.Open(RepositoryConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, repositoryParameters);

            using (Stream jsonFile = File.Open(WalletManagerConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, walletManagerParameters);

            using (Stream jsonFile = File.Open(NetworkConfigPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (StreamWriter writer = new StreamWriter(jsonFile))
                    using (JsonWriter jsonWriter = new JsonTextWriter(writer))
                        jsonSerializer.Serialize(jsonWriter, networkParametersFirst);

            JsonBasicMiningFactoryConfig       miningConfig        = new JsonBasicMiningFactoryConfig(MiningConfigPath);
            JsonBlockchainStorageManagerConfig managerConfig       = new JsonBlockchainStorageManagerConfig(ManagerConfigPath);
            JsonUnitRepositoryConfig           repositoryConfig    = new JsonUnitRepositoryConfig(RepositoryConfigPath);
            JsonWalletManagerConfig            walletManagerConfig = new JsonWalletManagerConfig(WalletManagerConfigPath);
            JsonNetworkConfig networkConfig = new JsonNetworkConfig(NetworkConfigPath);

            #endregion

            IMiningFactory    miningFactory          = new BasicMiningFactory(miningConfig);
            IHashFactory      hashFactory            = miningFactory.GetMiningHashFactoryById(3);
            IHashFactory      transactionHashFactory = new TransactionHashFactory();
            ISignatureFactory signatureFactory       = new ECDSAFactory();
            IWalletManager    walletManager          = new WalletManager(walletManagerConfig, signatureFactory, transactionHashFactory);

            Wallet                   wallet         = walletManager.GetWallets().First();
            UnitRepository           repository     = new UnitRepository(repositoryConfig);
            BlockchainStorageManager storageManager = new BlockchainStorageManager(managerConfig, repository);
            Blockchain               blockchain     = new Blockchain(wallet, walletManager, transactionHashFactory, signatureFactory, miningFactory, storageManager);

            wallet.Blockchain = blockchain;

            #region Network.

            AddressBook  addressBook = new AddressBook(AddressBookPath);
            IBroadcaster network     = new Network(blockchain, addressBook, networkConfig, wallet.Signer);

            blockchain.NetworkBroadcaster = network;

            network.Start();

            #endregion

            Console.WriteLine("Second");
            Console.WriteLine("0 - send transaction;\n1 - mine new block;\n2 - validate blockchain;\n3 - count your balance;\n4 - quit\n5 - create new wallet");

            string input;

            do
            {
                input = Console.ReadLine();

                switch (input)
                {
                case "0":
                    wallet.SendTokens(8, addressBook.First().Key.PublicKey);

                    break;

                case "1":
                    blockchain.ProcessPendingTransactions();

                    break;

                case "2":
                    Console.WriteLine(blockchain.IsValid ? "Blockchain is valid" : "Blockchain is invalid");

                    break;

                case "3":
                    Console.WriteLine(blockchain.CountBalanceForWallet(wallet.PublicKey));

                    break;

                case "4":
                    Console.WriteLine("Bye!");

                    break;

                case "5":
                    Wallet newOne = walletManager.AddNewWallet();

                    Console.WriteLine("New wallet created!");
                    Console.WriteLine($"Public key: {hashFactory.GetByteConverter().ConvertToString(newOne.PublicKey)}");

                    break;

                default:
                    Console.WriteLine("Wrong input!");

                    break;
                }
            }while (input != "4");

            network.Stop();
        }
Пример #25
0
 public static Transaction GetTransaction(object txid)
 {
     byte[] _txid = (byte[])txid;
     return(Blockchain.GetTransaction(_txid));
 }
Пример #26
0
        public (Transaction, string) CreateTransaction(string recipientAddress, decimal amountToSend, Blockchain blockchain)
        {
            Balance = CalculateBalance(blockchain);

            if (amountToSend > Balance)
            {
                return(null, $"Amount {amountToSend} exceeds balance");
            }

            (bool, Transaction)response = TransactionPool.Instance.ExistingTransaction(PublicKey.Key);
            Transaction transaction = response.Item2;

            if (response.Item1)
            {
                transaction.UpdateTransaction(this, recipientAddress, amountToSend);
            }
            else
            {
                transaction = new Transaction();
                transaction.CreateTransaction(this, recipientAddress, amountToSend);
            }

            TransactionPool.Instance.UpdateOrAddTransaction(transaction);

            return(transaction, $"Transaction created successfully");
        }
Пример #27
0
        public static Header GetHeaderByHeight(object height)
        {
            uint _height = (uint)height;

            return(Blockchain.GetHeader(_height));
        }
Пример #28
0
 public Emulator(Blockchain blockchain)
 {
     this.blockchain = blockchain;
     this.interop    = new InteropService();
 }
Пример #29
0
        public static object Main(string operation, object[] args)
        {
            if (Runtime.Trigger == TriggerType.Application)
            {
                var callscript = ExecutionEngine.CallingScriptHash;

                //查询可解锁资产
                if (operation == "getCanWithdrawAmount")//locker,assetId
                {
                    byte[] locker  = (byte[])args[0];
                    byte[] assetId = (byte[])args[1];

                    BigInteger unlockInterval = GetUnlockInterval(locker, assetId);
                    if (unlockInterval <= 0)
                    {
                        return(false);
                    }
                    BigInteger unlockAmount = GetUnlockAmount(locker, assetId);
                    if (unlockAmount <= 0)
                    {
                        return(false);
                    }

                    Header header = Blockchain.GetHeader(Blockchain.GetHeight());

                    BigInteger lockTimestamp = GetLockTimestamp(locker, assetId);
                    if (lockTimestamp <= 0 || header.Timestamp <= lockTimestamp)
                    {
                        return(false);
                    }

                    BigInteger timeInterval = header.Timestamp - lockTimestamp;

                    var lockBalance = GetBalance(locker, assetId);

                    if (lockBalance <= 0)
                    {
                        return(false);
                    }

                    if (timeInterval < unlockInterval)
                    {
                        return(0);
                    }

                    BigInteger multiple = timeInterval / unlockInterval;

                    BigInteger withdrawAmount = multiple * unlockAmount;

                    if (lockBalance < withdrawAmount)
                    {
                        withdrawAmount = lockBalance;
                    }

                    return(withdrawAmount);
                }

                //查询解锁条件
                if (operation == "getUnlockInterval")// locker,assetId
                {
                    return(GetUnlockInterval((byte[])args[0], (byte[])args[1]));
                }
                if (operation == "getUnlockAmount")// locker,assetId
                {
                    return(GetUnlockAmount((byte[])args[0], (byte[])args[1]));
                }

                //查询当前锁仓数额
                if (operation == "getLockAomunt") // locker,assetId
                {
                    return(GetBalance((byte[])args[0], (byte[])args[1]));
                }

                //查询上次锁仓刷新时间
                if (operation == "getLockTimestamp")// locker,assetId
                {
                    return(GetLockTimestamp((byte[])args[0], (byte[])args[1]));
                }

                //设置提取条件 提取地址,资产ID,解锁间隔,每次解锁数额
                if (operation == "setCondition") // locker,assetID,unlockInterval,unlockAmount
                {
                    if (args.Length != 4)
                    {
                        return(false);
                    }
                    if (!Runtime.CheckWitness(superAdmin))
                    {
                        return(false);
                    }
                    return(SetCondition((byte[])args[0], (byte[])args[1], (BigInteger)args[2], (BigInteger)args[3]));
                }

                //管理员可以取走全部资产
                if (operation == "withdrawAll") // locker, assetId, toAddress, isGlobal
                {
                    if (args.Length != 4)
                    {
                        return(false);
                    }
                    if (!Runtime.CheckWitness(superAdmin))
                    {
                        return(false);
                    }
                    WithdrawalAll((byte[])args[0], (byte[])args[1], (byte[])args[2], (BigInteger)args[3]);
                    return(true);
                }

                //管理员设置锁仓开始时间为当前区块时间
                if (operation == "setLockTimestamp") // locker, assetId
                {
                    if (args.Length != 2)
                    {
                        return(false);
                    }
                    if (!Runtime.CheckWitness(superAdmin))
                    {
                        return(false);
                    }
                    SetLockTimestamp((byte[])args[0], (byte[])args[1]);
                    return(true);
                }

                //存钱 锁仓
                if (operation == "lock") // (txid, locker, assetID, isGlobal)
                {
                    if (args.Length != 4)
                    {
                        return(false);
                    }
                    if (!Runtime.CheckWitness(superAdmin))
                    {
                        return(false);
                    }
                    return(Lock((byte[])args[0], (byte[])args[1], (byte[])args[2], (BigInteger)args[3]));
                }

                //取钱 提现
                if (operation == "withdraw") // locker, assetId, address, isGlobal
                {
                    if (args.Length != 4)
                    {
                        return(false);
                    }

                    byte[] locker = (byte[])args[0];
                    if (!Runtime.CheckWitness(locker))
                    {
                        return(false);
                    }

                    byte[] assetId   = (byte[])args[1];
                    byte[] toAddress = (byte[])args[2];
                    if (toAddress.Length != 20)
                    {
                        return(false);
                    }

                    BigInteger unlockInterval = GetUnlockInterval(locker, assetId);
                    if (unlockInterval <= 0)
                    {
                        return(false);
                    }
                    BigInteger unlockAmount = GetUnlockAmount(locker, assetId);
                    if (unlockAmount <= 0)
                    {
                        return(false);
                    }

                    Header header = Blockchain.GetHeader(Blockchain.GetHeight());

                    BigInteger lockTimestamp = GetLockTimestamp(locker, assetId);
                    if (lockTimestamp <= 0 || header.Timestamp <= lockTimestamp)
                    {
                        return(false);
                    }

                    BigInteger timeInterval = header.Timestamp - lockTimestamp;

                    var lockBalance = GetBalance(locker, assetId);

                    if (lockBalance <= 0)
                    {
                        return(false);
                    }

                    if (timeInterval < unlockInterval)
                    {
                        return(false);
                    }

                    BigInteger multiple = timeInterval / unlockInterval;

                    BigInteger withdrawAmount = multiple * unlockAmount;

                    if (lockBalance < withdrawAmount)
                    {
                        withdrawAmount = lockBalance;
                    }

                    return(Withdrawal(locker, assetId, toAddress, withdrawAmount, (BigInteger)args[3]));
                }
            }
            return(false);
        }
Пример #30
0
 public WebSocketHandler(Blockchain blockchain, ILogger <WebSocketHandler> logger)
 {
     _blockchain = blockchain;
     _logger     = logger;
 }
Пример #31
0
 public BlockchainKey WriteBlockchain(Blockchain blockchain)
 {
     throw new NotImplementedException();
 }
Пример #32
0
        protected internal override void OnStart(string[] args)
        {
            Blockchain.RegisterBlockchain(new LevelDBBlockchain(Settings.Default.Paths.Chain));
            if (!args.Contains("--nopeers") && File.Exists(PeerStatePath))
            {
                using (FileStream fs = new FileStream(PeerStatePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    LocalNode.LoadState(fs);
                }
            }
            LocalNode = new LocalNode();
            Task.Run(() =>
            {
                const string acc_path     = "chain.acc";
                const string acc_zip_path = acc_path + ".zip";
                if (File.Exists(acc_path))
                {
                    using (FileStream fs = new FileStream(acc_path, FileMode.Open, FileAccess.Read, FileShare.None))
                    {
                        ImportBlocks(fs);
                    }
                    File.Delete(acc_path);
                }
                else if (File.Exists(acc_zip_path))
                {
                    using (FileStream fs = new FileStream(acc_zip_path, FileMode.Open, FileAccess.Read, FileShare.None))
                        using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                            using (Stream zs = zip.GetEntry(acc_path).Open())
                            {
                                ImportBlocks(zs);
                            }
                    File.Delete(acc_zip_path);
                }
                LocalNode.Start(Settings.Default.P2P.Port, Settings.Default.P2P.WsPort);
                bool log = false;
                for (int i = 0; i < args.Length; i++)
                {
                    switch (args[i])
                    {
                    case "/rpc":
                    case "--rpc":
                    case "-r":
                        if (rpc == null)
                        {
                            rpc = new RpcServerWithWallet(LocalNode);
                            rpc.Start(Settings.Default.RPC.Port, Settings.Default.RPC.SslCert, Settings.Default.RPC.SslCertPassword);
                        }
                        break;

                    case "-l":
                    case "--log":
                        log = true;
                        break;
                    }
                }
                if (log)
                {
                    LevelDBBlockchain.ApplicationExecuted += LevelDBBlockchain_ApplicationExecuted;
                }
            });
        }