Exemple #1
0
 public static Props Props(ZoroSystem system, Store store, UInt160 chainHash)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new Blockchain(system, store, chainHash)).WithMailbox("blockchain-mailbox"));
     }
 }
Exemple #2
0
 public static Props Props(ZoroSystem system, UInt160 chainHash)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new LocalNode(system, chainHash)));
     }
 }
Exemple #3
0
        private void CreateLogger(UInt160 chainHash)
        {
            if (!dbs.ContainsKey(chainHash))
            {
                // 根据链的Hash,获取对应的ZoroSystem对象
                ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(chainHash);
                if (system != null)
                {
                    // 用MagicNumber加上ChainHash作为ApplicationLog数据库的文件名
                    string path = string.Format(Settings.Default.Path, Message.Magic.ToString("X8"), chainHash.ToArray().Reverse().ToHexString());

                    string relativePath = Settings.Default.RelativePath;
                    if (relativePath.Length > 0)
                    {
                        path = relativePath + path;
                    }

                    Directory.CreateDirectory(path);

                    DB db = DB.Open(Path.GetFullPath(path), new Options {
                        CreateIfMissing = true
                    });

                    dbs.TryAdd(chainHash, db);
                }

                PluginManager.Singleton.SendMessage(dbs);
            }
        }
Exemple #4
0
 public static Props Props(ZoroSystem system, UInt160 chainHash)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new TaskManager(system, chainHash)).WithMailbox("task-manager-mailbox"));
     }
 }
Exemple #5
0
        private void CreateSpider(UInt160 chainHash)
        {
            if (!spiders.ContainsKey(chainHash))
            {
                ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(chainHash);
                if (system != null)
                {
                    IActorRef logger = system.ActorOf(Spider.Props(this, system.Blockchain, chainHash));
                    spiders.TryAdd(chainHash, logger);
                }
            }

            TransactionDal tran = new TransactionDal();

            try
            {
                tran.BeginTransaction();
                AppChainListSpider appChainListSpider = new AppChainListSpider();
                appChainListSpider.Start(tran.conn);
                tran.CommitTransaction();
            }
            catch (Exception e)
            {
                tran.RollbackTransaction();
                throw e;
            }
        }
Exemple #6
0
 public static Props Props(ZoroSystem system, LocalNode localNode, Blockchain blockchain)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new ProtocolHandler(system, localNode, blockchain)).WithMailbox("protocol-handler-mailbox"));
     }
 }
Exemple #7
0
 public static Props Props(ZoroSystem system, Wallet wallet, UInt160 chainHash)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new ConsensusService(system, wallet, chainHash)).WithMailbox("consensus-service-mailbox"));
     }
 }
Exemple #8
0
        public LocalNode(ZoroSystem system, UInt160 chainHash)
        {
            lock (lockObj)
            {
                this.system    = system;
                this.ChainHash = chainHash;

                if (chainHash.Equals(UInt160.Zero))
                {
                    if (root != null)
                    {
                        throw new InvalidOperationException();
                    }

                    root = this;

                    SeedList = ProtocolSettings.Default.SeedList;
                }
                else
                {
                    AppChainState state = ZoroChainSystem.Singleton.RegisterAppChainLocalNode(chainHash, this);

                    SeedList = state.SeedList;
                }

                Blockchain = ZoroChainSystem.Singleton.AskBlockchain(chainHash);
            }

            LoadRecentPeers();
        }
Exemple #9
0
        public LocalNode(ZoroSystem system, UInt160 chainHash)
        {
            lock (GetType())
            {
                this.system     = system;
                this.ChainHash  = chainHash;
                this.Blockchain = Blockchain.GetBlockchain(chainHash);

                if (root == null)
                {
                    root = this;

                    this.SeedList = Settings.Default.SeedList;
                }
                else
                {
                    if (chainHash.Size == 0)
                    {
                        throw new ArgumentException();
                    }

                    RegisterAppNode(chainHash, this);
                }
            }
        }
Exemple #10
0
 internal static Props Props(ZoroSystem system, object connection, IPEndPoint remote, IPEndPoint local, LocalNode localNode)
 {
     lock (ZoroSystem.Sync)
     {
         return(Akka.Actor.Props.Create(() => new RemoteNode(system, connection, remote, local, localNode)).WithMailbox("remote-node-mailbox"));
     }
 }
Exemple #11
0
 public ConsensusService(ZoroSystem system, Wallet wallet, UInt160 chainHash)
 {
     this.system     = system;
     this.wallet     = wallet;
     this.chainHash  = chainHash;
     this.localNode  = LocalNode.GetLocalNode(chainHash);
     this.blockchain = Blockchain.GetBlockchain(chainHash);
 }
Exemple #12
0
        public static async Task <RelayResultReason> InvokeRawTransaction(InvocationTransaction tx, string chainHash)
        {
            ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(chainHash);

            RelayResultReason reason = await system.Blockchain.Ask <RelayResultReason>(tx);

            return(reason);
        }
Exemple #13
0
 public RemoteNode(ZoroSystem system, object connection, IPEndPoint remote, IPEndPoint local, LocalNode localNode)
     : base(connection, remote, local)
 {
     this.system    = system;
     this.localNode = localNode;
     this.protocol  = Context.ActorOf(ProtocolHandler.Props(system, localNode, localNode.Blockchain));
     localNode.RemoteNodes.TryAdd(Self, this);
     SendMessage(Message.Create("version", VersionPayload.Create(localNode.ListenerPort, LocalNode.Nonce, LocalNode.UserAgent, localNode.Blockchain.Height)));
 }
Exemple #14
0
        public Blockchain(ZoroSystem system, Store store, UInt160 chainHash)
        {
            this.ChainHash   = chainHash;
            this.system      = system;
            this.Store       = store;
            store.Blockchain = this;

            if (root == null)
            {
                root = this;
                StandbyValidators = Settings.Default.StandbyValidators.OfType <string>().Select(p => ECPoint.DecodePoint(p.HexToBytes(), ECCurve.Secp256r1)).ToArray();
            }
            else
            {
                if (chainHash.Size == 0)
                {
                    throw new ArgumentException();
                }

                RegisterAppChain(chainHash, this);
            }

            GenesisBlock.RebuildMerkleRoot();

            lock (GetType())
            {
                header_index.AddRange(store.GetHeaderHashList().Find().OrderBy(p => (uint)p.Key).SelectMany(p => p.Value.Hashes));
                stored_header_count += (uint)header_index.Count;
                if (stored_header_count == 0)
                {
                    header_index.AddRange(store.GetBlocks().Find().OrderBy(p => p.Value.TrimmedBlock.Index).Select(p => p.Key));
                }
                else
                {
                    HashIndexState hashIndex = store.GetHeaderHashIndex().Get();
                    if (hashIndex.Index >= stored_header_count)
                    {
                        DataCache <UInt256, BlockState> cache = store.GetBlocks();
                        for (UInt256 hash = hashIndex.Hash; hash != header_index[(int)stored_header_count - 1];)
                        {
                            header_index.Insert((int)stored_header_count, hash);
                            hash = cache[hash].TrimmedBlock.PrevHash;
                        }
                    }
                }

                if (header_index.Count == 0)
                {
                    Persist(GenesisBlock);
                }
                else
                {
                    UpdateCurrentSnapshot();
                }
            }
        }
Exemple #15
0
        public ProtocolHandler(ZoroSystem system, LocalNode localNode, Blockchain blockchain, RemoteNode remoteNode)
        {
            this.system     = system;
            this.localNode  = localNode;
            this.blockchain = blockchain;
            this.remoteNode = remoteNode;

            InitMessageHandlers();

            this.knownHashes = new FIFOSet <UInt256>(blockchain.MemPool.Capacity * 2);
            this.sentHashes  = new FIFOSet <UInt256>(blockchain.MemPool.Capacity * 2);
        }
Exemple #16
0
        public RemoteNode(ZoroSystem system, object connection, IPEndPoint remote, IPEndPoint local, Blockchain blockchain, LocalNode localNode)
            : base(connection, remote, local)
        {
            this.system     = system;
            this.localNode  = localNode;
            this.blockchain = blockchain;

            this.protocol = Context.ActorOf(ProtocolHandler.Props(system, localNode, blockchain, this), "RemoteNode");
            localNode.RemoteNodes.TryAdd(Self, this);

            SendMessage(Message.Create(MessageType.Version, VersionPayload.Create(localNode.ChainHash, localNode.ListenerPort, LocalNode.NodeId, LocalNode.UserAgent, blockchain.Height)));

            Log($"Connected to RemoteNode {blockchain.Name} {remote}");
        }
Exemple #17
0
        private bool OnRelayCommand(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("You must input JSON object to relay.");
                return(true);
            }
            string     hashString = args[1];
            ZoroSystem zoroSystem = system.GetZoroSystem(hashString);

            if (zoroSystem == null)
            {
                Console.WriteLine($"Unknown blockchain hash {hashString}.");
                return(true);
            }

            var jsonObjectToRelay = string.Join(string.Empty, args.Skip(2));

            if (string.IsNullOrWhiteSpace(jsonObjectToRelay))
            {
                Console.WriteLine("You must input JSON object to relay.");
                return(true);
            }
            try
            {
                ContractParametersContext context = ContractParametersContext.Parse(jsonObjectToRelay);
                if (!context.Completed)
                {
                    Console.WriteLine("The signature is incomplete.");
                    return(true);
                }
                if (!(context.Verifiable is Transaction tx))
                {
                    Console.WriteLine($"Only support to relay transaction.");
                    return(true);
                }
                tx.Witnesses = context.GetWitnesses();
                zoroSystem.LocalNode.Tell(new LocalNode.Relay {
                    Inventory = tx
                });
                Console.WriteLine($"Data relay success, the hash is shown as follows:\r\n{tx.Hash}");
            }
            catch (Exception e)
            {
                Console.WriteLine($"One or more errors occurred:\r\n{e.Message}");
            }
            return(true);
        }
Exemple #18
0
        private RelayResultReason SubmitInvocationTransaction(UInt160 chainHash, KeyPair keyPair, byte[] script)
        {
            ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(chainHash);

            Blockchain blockchain = ZoroChainSystem.Singleton.GetBlockchain(chainHash);

            InvocationTransaction tx = new InvocationTransaction
            {
                Nonce    = Transaction.GetNonce(),
                Account  = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(),
                Script   = script,
                GasLimit = InvocationTransaction.GetGasLimit(Fixed8.Zero),
            };

            tx.Attributes          = new TransactionAttribute[1];
            tx.Attributes[0]       = new TransactionAttribute();
            tx.Attributes[0].Usage = TransactionAttributeUsage.Script;
            tx.Attributes[0].Data  = tx.Account.ToArray();

            ContractParametersContext context = new ContractParametersContext(tx, blockchain);

            Program.Wallet.Sign(context);
            if (context.Completed)
            {
                tx.Witnesses = context.GetWitnesses();

                RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result;

                if (reason != RelayResultReason.Succeed)
                {
                    Console.WriteLine($"Local Node could not relay transaction: {GetRelayResult(reason)}");
                }
                else
                {
                    Console.WriteLine($"Transaction has been accepted.");
                }
                return(reason);
            }

            return(RelayResultReason.UnableToVerify);
        }
Exemple #19
0
 public RpcServer(ZoroSystem system, Wallet wallet = null)
 {
     this.system = system;
     this.wallet = wallet;
 }
Exemple #20
0
 public TaskManager(ZoroSystem system, UInt160 chainHash)
 {
     this.system     = system;
     this.chainHash  = chainHash;
     this.blockchain = ZoroChainSystem.Singleton.AskBlockchain(chainHash);
 }
Exemple #21
0
        private bool OnImport(string[] args)
        {
            if (args.Length < 3)
            {
                return(false);
            }
            if (!string.Equals(args[1], "block", StringComparison.OrdinalIgnoreCase) &&
                !string.Equals(args[1], "blocks", StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            string filename = args[2];

            Task.Run(() =>
            {
                var paths = Directory.EnumerateFiles(".", filename, 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)
                {
                    Blockchain blockchain = ZoroChainSystem.Singleton.GetBlockchain(GetChainHash(path.FileName));
                    if (blockchain == null)
                    {
                        continue;
                    }

                    if (path.Start > blockchain.Height + 1)
                    {
                        break;
                    }
                    if (path.IsCompressed)
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                            using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
                                using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open())
                                {
                                    ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(GetChainHash(path.FileName));
                                    if (system != null)
                                    {
                                        system.Blockchain.Ask <Blockchain.ImportCompleted>(new Blockchain.Import
                                        {
                                            Blocks = GetBlocks(blockchain, zs)
                                        }).Wait();
                                    }
                                }
                    }
                    else
                    {
                        using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            ZoroSystem system = ZoroChainSystem.Singleton.GetZoroSystem(GetChainHash(path.FileName));
                            if (system != null)
                            {
                                system.Blockchain.Ask <Blockchain.ImportCompleted>(new Blockchain.Import
                                {
                                    Blocks = GetBlocks(blockchain, fs)
                                }).Wait();
                            }
                        }
                    }
                }
            });

            return(true);
        }
Exemple #22
0
 public static Props Props(ZoroSystem system)
 {
     return(Akka.Actor.Props.Create(() => new TransactionDispatcher(system)));
 }
Exemple #23
0
 public TaskManager(ZoroSystem system, UInt160 chainHash)
 {
     this.system     = system;
     this.chainHash  = chainHash;
     this.blockchain = Blockchain.GetBlockchain(chainHash);
 }
Exemple #24
0
        private JObject SubmitBlock(ZoroSystem system, Block block)
        {
            RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(block).Result;

            return(GetRelayResult(reason));
        }
Exemple #25
0
        private JObject SendRawTransaction(ZoroSystem system, Transaction tx)
        {
            RelayResultReason reason = system.Blockchain.Ask <RelayResultReason>(tx).Result;

            return(GetRelayResult(reason));
        }
Exemple #26
0
        public JObject Process(string method, JArray _params)
        {
            try
            {
                switch (method)
                {
                case "getbestblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBestBlockHash(blockchain));
                }

                case "getblock":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlock(blockchain, key, verbose));
                }

                case "getblockcount":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetBlockCount(blockchain));
                }

                case "getblockhash":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockHash(blockchain, height));
                }

                case "getblockheader":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    JObject    key        = _params[1];
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetBlockHeader(blockchain, key, verbose));
                }

                case "getblocksysfee":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    uint       height     = uint.Parse(_params[1].AsString());
                    return(GetBlockSysFee(blockchain, height));
                }

                case "getconnectioncount":
                {
                    LocalNode localNode = GetTargetNode(_params[0]);
                    return(localNode != null ? localNode.ConnectedCount : 0);
                }

                case "getcontractstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    return(GetContractState(blockchain, script_hash));
                }

                case "getpeers":
                {
                    return(GetPeers(_params[0]));
                }

                case "getrawmempool":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPool(blockchain, shouldGetUnverified));
                }

                case "getrawmempoolcount":
                {
                    Blockchain blockchain          = GetTargetChain(_params[0]);
                    bool       shouldGetUnverified = _params.Count >= 2 && _params[1].AsBoolean();
                    return(GetRawMemPoolCount(blockchain, shouldGetUnverified));
                }

                case "getrawtransaction":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    bool       verbose    = _params.Count >= 3 && _params[2].AsBoolean();
                    return(GetRawTransaction(blockchain, hash, verbose));
                }

                case "getstorage":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[1].AsString());
                    byte[]     key         = _params[2].AsString().HexToBytes();
                    return(GetStorage(blockchain, script_hash, key));
                }

                case "gettransactionheight":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    UInt256    hash       = UInt256.Parse(_params[1].AsString());
                    return(GetTransactionHeight(blockchain, hash));
                }

                case "getvalidators":
                {
                    Blockchain blockchain = GetTargetChain(_params[0]);
                    return(GetValidators(blockchain));
                }

                case "getversion":
                {
                    return(GetVersion());
                }

                case "invokefunction":
                {
                    UInt160             script_hash = UInt160.Parse(_params[1].AsString());
                    string              operation   = _params[2].AsString();
                    ContractParameter[] args        = _params.Count >= 4 ? ((JArray)_params[3]).Select(p => ContractParameter.FromJson(p)).ToArray() : new ContractParameter[0];
                    return(InvokeFunction(_params[0], script_hash, operation, args));
                }

                case "invokescript":
                {
                    byte[] script = _params[1].AsString().HexToBytes();
                    return(InvokeScript(_params[0], script));
                }

                case "listplugins":
                {
                    return(ListPlugins());
                }

                case "sendrawtransaction":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Transaction tx = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                        return(SendRawTransaction(targetSystem, tx));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "submitblock":
                {
                    ZoroSystem targetSystem = GetTargetSystem(_params[0]);
                    if (targetSystem != null)
                    {
                        Block block = _params[0].AsString().HexToBytes().AsSerializable <Block>();
                        return(SubmitBlock(targetSystem, block));
                    }
                    return(RelayResultReason.Invalid);
                }

                case "validateaddress":
                {
                    string address = _params[0].AsString();
                    return(ValidateAddress(address));
                }

                case "getappchainhashlist":
                {
                    return(GetAppChainHashList());
                }

                case "getappchainstate":
                {
                    Blockchain blockchain  = GetTargetChain(_params[0]);
                    UInt160    script_hash = UInt160.Parse(_params[0].AsString());
                    return(GetAppChainState(blockchain, script_hash));
                }

                case "getappchainlist":
                {
                    return(GetAppChainList());
                }

                case "getappchainlistenerports":
                {
                    return(GetAppChainListenerPorts());
                }

                case "estimategas":
                {
                    Blockchain  blockchain = GetTargetChain(_params[0]);
                    Transaction tx         = Transaction.DeserializeFrom(_params[1].AsString().HexToBytes());
                    return(GetEstimateGas(blockchain, tx));
                }

                default:
                    throw new RpcException(-32601, "Method not found");
                }
            }
            catch (Exception ex)
            {
                JObject json = new JObject();
                json["message"] = ex.Message;
                json["method"]  = method;
                json["source"]  = ex.Source;
                return(json);
            }
        }
Exemple #27
0
 public TransactionDispatcher(ZoroSystem system)
 {
     this.system = system;
 }
Exemple #28
0
        private bool OnBroadcastCommand(string[] args)
        {
            string     command    = args[1].ToLower();
            string     hashString = args[2];
            ZoroSystem zoroSystem = system.GetZoroSystem(hashString);
            Blockchain blockchain = system.GetBlockchain(hashString);

            if (zoroSystem == null || blockchain == null)
            {
                Console.WriteLine($"Unknown blockchain hash {hashString}.");
                return(true);
            }
            ISerializable payload = null;

            switch (command)
            {
            case "addr":
                payload = AddrPayload.Create(NetworkAddressWithTime.Create(new IPEndPoint(IPAddress.Parse(args[3]), ushort.Parse(args[4])), NetworkAddressWithTime.NODE_NETWORK, DateTime.UtcNow.ToTimestamp()));
                break;

            case "block":
                if (args[3].Length == 64 || args[3].Length == 66)
                {
                    payload = blockchain.GetBlock(UInt256.Parse(args[3]));
                }
                else
                {
                    payload = blockchain.Store.GetBlock(uint.Parse(args[3]));
                }
                break;

            case "getblocks":
            case "getheaders":
                payload = GetBlocksPayload.Create(UInt256.Parse(args[3]));
                break;

            case "getdata":
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[3], true), UInt256.Parse(args[4]));
                break;

            case "inv":
            case "getdatagroup":
                payload = InvPayload.Create(Enum.Parse <InventoryType>(args[3], true), args.Skip(4).Select(UInt256.Parse).ToArray());
                break;

            case "tx":
                payload = blockchain.GetTransaction(UInt256.Parse(args[3]));
                break;

            case "alert":
            case "consensus":
            case "filteradd":
            case "filterload":
            case "headers":
            case "merkleblock":
            case "ping":
            case "pong":
            case "reject":
            case "verack":
            case "version":
                Console.WriteLine($"Command \"{command}\" is not supported.");
                return(true);
            }
            zoroSystem.LocalNode.Tell(Message.Create(command, payload));
            return(true);
        }
Exemple #29
0
 public PluginManager(ZoroSystem system, UInt160 chainHash)
 {
     System    = system;
     ChainHash = chainHash;
 }
Exemple #30
0
 public ProtocolHandler(ZoroSystem system, LocalNode localNode, Blockchain blockchain)
 {
     this.system     = system;
     this.localNode  = localNode;
     this.blockchain = blockchain;
 }