示例#1
0
        public int GetChainStatus(Hash chainId)
        {
            Api.Assert(_sideChainInfos.GetValue(chainId) != null, "Not existed side chain.");
            var info = _sideChainInfos[chainId];

            return((int)info.Status);
        }
示例#2
0
        public void WriteParentChainBlockInfo(ParentChainBlockInfo parentChainBlockInfo)
        {
            ulong parentChainHeight = parentChainBlockInfo.Height;
            var   currentHeight     = _currentParentChainHeight.GetValue();
            var   target            = currentHeight != 0 ? currentHeight + 1: GlobalConfig.GenesisBlockHeight;

            Api.Assert(target == parentChainHeight,
                       $"Parent chain block info at height {target} is needed, not {parentChainHeight}");
            Console.WriteLine("ParentChainBlockInfo.Height is correct.");

            var key = new UInt64Value {
                Value = parentChainHeight
            };

            Api.Assert(_parentChainBlockInfo.GetValue(key) == null,
                       $"Already written parent chain block info at height {parentChainHeight}");
            Console.WriteLine("Writing ParentChainBlockInfo..");
            foreach (var _ in parentChainBlockInfo.IndexedBlockInfo)
            {
                BindParentChainHeight(_.Key, parentChainHeight);
                AddIndexedTxRootMerklePathInParentChain(_.Key, _.Value);
            }
            _parentChainBlockInfo.SetValueAsync(key, parentChainBlockInfo).Wait();
            _currentParentChainHeight.SetValue(parentChainHeight);

            // only for debug
            Console.WriteLine($"WriteParentChainBlockInfo success at {parentChainHeight}");
        }
示例#3
0
        public async Task <byte[]> DeploySmartContract(int category, byte[] contract)
        {
            SmartContractRegistration registration = new SmartContractRegistration
            {
                Category      = category,
                ContractBytes = ByteString.CopyFrom(contract),
                ContractHash  = Hash.FromRawBytes(contract)
            };

            var tx = Api.GetTransaction();

            ulong serialNumber = _serialNumber.Increment().Value;

            var creator = Api.GetTransaction().From;

            var info = new ContractInfo()
            {
                Owner        = creator,
                SerialNumber = serialNumber
            };

            var address = info.Address;
            // calculate new account address
            var account = DataPath.CalculateAccountAddress(tx.From, tx.IncrementId);

            await Api.DeployContractAsync(account, registration);

            Console.WriteLine("TestContractZero: Deployment success, {0}", account.DumpHex());
            return(account.DumpByteArray());
        }
示例#4
0
        public ulong LockedToken(Hash chainId)
        {
            Api.Assert(_sideChainInfos.GetValue(chainId) != null, "Not existed side chain.");
            var info = _sideChainInfos[chainId];

            Api.Assert(info.Status != (SideChainStatus)3, "Disposed side chain.");
            return(info.LockedToken);
        }
示例#5
0
        public byte[] LockedAddress(Hash chainId)
        {
            Api.Assert(_sideChainInfos.GetValue(chainId) != null, "Not existed side chain.");
            var info = _sideChainInfos[chainId];

            Api.Assert(info.Status != (SideChainStatus)3, "Disposed side chain.");
            return(info.LockedAddress.DumpByteArray());
        }
示例#6
0
        public static void Reduce(Address owner, ulong amount)
        {
            var pair = new AddressPair()
            {
                First = owner, Second = Api.GetTransaction().From
            };

            _allowances[pair] = _allowances[pair].Sub(amount);
        }
示例#7
0
        public static void Approve(Address spender, ulong amount)
        {
            var pair = new AddressPair()
            {
                First = Api.GetTransaction().From, Second = spender
            };

            _allowances[pair] = _allowances[pair].Add(amount);
        }
示例#8
0
        public void TransferFrom(Address from, Address to, ulong amount)
        {
            var allowance = Allowances.GetAllowance(from, Api.GetTransaction().From);

            Api.Assert(allowance > amount, "Insufficient allowance.");

            DoTransfer(from, to, amount);
            Allowances.Reduce(from, amount);
        }
示例#9
0
 public void UnApprove(Address spender, ulong amount)
 {
     Allowances.Reduce(spender, amount);
     new UnApproved()
     {
         Owner   = Api.GetTransaction().From,
         Spender = spender,
         Amount  = amount
     }.Fire();
 }
示例#10
0
        public async Task <object> GetTransactionEndTime(Hash transactionHash)
        {
            var endTime = await TransactionEndTimes.GetValue(transactionHash);

            Api.Return(new BytesValue()
            {
                Value = ByteString.CopyFrom(endTime)
            });
            return(endTime);
        }
示例#11
0
        public async Task <object> GetBalance(Hash account)
        {
            var balBytes = await Balances.GetValue(account);

            Api.Return(new UInt64Value()
            {
                Value = balBytes.ToUInt64()
            });
            return(balBytes.ToUInt64());
        }
示例#12
0
 public void Initialize(string symbol, string tokenName, ulong totalSupply, uint decimals)
 {
     Api.Assert(!_initialized.GetValue(), "Already initialized.");
     // Api.Assert(Api.GetContractOwner().Equals(Api.GetTransaction().From), "Only owner can initialize the contract state.");
     _symbol.SetValue(symbol);
     _tokenName.SetValue(tokenName);
     _totalSupply.SetValue(totalSupply);
     _decimals.SetValue(decimals);
     _balances[Api.GetTransaction().From] = totalSupply;
     _initialized.SetValue(true);
 }
示例#13
0
        private void AddIndexedTxRootMerklePathInParentChain(ulong height, MerklePath path)
        {
            var key = new UInt64Value {
                Value = height
            };

            Api.Assert(_txRootMerklePathInParentChain.GetValue(key) == null,
                       $"Merkle path already bound at height {height}.");
//            _txRootMerklePathInParentChain[key] = path;
            _txRootMerklePathInParentChain.SetValueAsync(key, path).Wait();
            Console.WriteLine("Path: {0}", path.Path[0].DumpHex());
        }
示例#14
0
        private void BindParentChainHeight(ulong childHeight, ulong parentHeight)
        {
            var key = new UInt64Value {
                Value = childHeight
            };

            Api.Assert(_childHeightToParentChainHeight.GetValue(key) == null,
                       $"Already bound at height {childHeight} with parent chain");
//            _childHeightToParentChainHeight[key] = new UInt64Value {Value = parentHeight};
            _childHeightToParentChainHeight.SetValueAsync(key, new UInt64Value {
                Value = parentHeight
            }).Wait();
        }
示例#15
0
        public void DisposeSideChain(Hash chainId)
        {
            Api.Assert(_sideChainInfos.GetValue(chainId) != null, "Not existed side chain");
            // TODO: Only privileged account can trigger this method
            var info = _sideChainInfos[chainId];

            info.Status = SideChainStatus.Terminated;
            _sideChainInfos[chainId] = info;
            new SideChainDisposal
            {
                chainId = chainId
            }.Fire();
        }
示例#16
0
        public override async Task InvokeAsync()
        {
            var tx = Api.GetTransaction();

            var methodname = tx.MethodName;
            var type       = GetType();
            var member     = type.GetMethod(methodname);
            // params array
            var parameters = Parameters.Parser.ParseFrom(tx.Params).Params.Select(p => p.Value()).ToArray();

            // invoke
            //await (Task<object>)member.Invoke(this, parameters);
            await(Task <object>) member.Invoke(this, parameters);
        }
示例#17
0
        public void ApproveSideChain(Hash chainId)
        {
            // TODO: Only privileged account can trigger this method
            var info = _sideChainInfos[chainId];

            Api.Assert(info != null, "Invalid chain id.");
            Api.Assert(info?.Status == SideChainStatus.Pending, "Invalid chain status.");
            info.Status = SideChainStatus.Active;
            _sideChainInfos[chainId] = info;
            new SideChainCreationRequestApproved()
            {
                Info = info.Clone()
            }.Fire();
        }
示例#18
0
        public bool VerifyTransaction(Hash tx, MerklePath path, ulong parentChainHeight)
        {
            var key = new UInt64Value {
                Value = parentChainHeight
            };

            Api.Assert(_parentChainBlockInfo.GetValue(key) != null,
                       $"Parent chain block at height {parentChainHeight} is not recorded.");
            var rootCalculated = path.ComputeRootWith(tx);
            var parentRoot     = _parentChainBlockInfo.GetValue(key)?.Root?.SideChainTransactionsRoot;

            //Api.Assert((parentRoot??Hash.Zero).Equals(rootCalculated), "Transaction verification Failed");
            return((parentRoot ?? Hash.Zero).Equals(rootCalculated));
        }
示例#19
0
        private void DoTransfer(Address from, Address to, ulong amount)
        {
            var balSender = _balances[from];

            Api.Assert(balSender >= amount, "Insufficient balance.");
            var balReceiver = _balances[to];

            balSender       = balSender.Sub(amount);
            balReceiver     = balReceiver.Add(amount);
            _balances[from] = balSender;
            _balances[to]   = balReceiver;
            new Transfered()
            {
                From   = from,
                To     = to,
                Amount = amount
            }.Fire();
        }
示例#20
0
        public void Transfer(Hash to, ulong amount)
        {
            var from      = Api.GetTransaction().From;
            var balSender = _balances[from];

            Api.Assert(balSender > amount, "Insufficient balance.");
            var balReceiver = _balances[to];

            balSender       = balSender.Sub(amount);
            balReceiver     = balReceiver.Add(amount);
            _balances[from] = balSender;
            _balances[to]   = balReceiver;
            new Transfered()
            {
                From   = from,
                To     = to,
                Amount = amount
            }.Fire();
        }
示例#21
0
        public byte[] CreateSideChain(Hash chainId, Address lockedAddress, ulong lockedToken)
        {
            ulong serialNumber = _sideChainSerialNumber.Increment().Value;
            var   info         = new SideChainInfo
            {
                Owner          = Api.GetTransaction().From,
                ChainId        = chainId,
                SerialNumer    = serialNumber,
                Status         = SideChainStatus.Pending,
                LockedAddress  = lockedAddress,
                LockedToken    = lockedToken,
                CreationHeight = Api.GetCurerntHeight() + 1
            };

            _sideChainInfos[chainId] = info;
            new SideChainCreationRequested()
            {
                ChainId = chainId,
                Creator = Api.GetTransaction().From
            }.Fire();
            return(chainId.DumpByteArray());
        }
示例#22
0
        public async Task <object> Transfer(Hash from, Hash to, ulong qty)
        {
            // This is for testing batched transaction sequence
            await TransactionStartTimes.SetValueAsync(Api.GetTransaction().GetHash(), Now());

            var fromBalBytes = await Balances.GetValue(from);

            var fromBal    = fromBalBytes.ToUInt64();
            var toBalBytes = await Balances.GetValue(to);

            var toBal      = toBalBytes.ToUInt64();
            var newFromBal = fromBal - qty;

            var newToBal = toBal + qty;
            await Balances.SetValueAsync(from, newFromBal.ToBytes());

            await Balances.SetValueAsync(to, newToBal.ToBytes());

            // This is for testing batched transaction sequence
            await TransactionEndTimes.SetValueAsync(Api.GetTransaction().GetHash(), Now());

            return(null);
        }
示例#23
0
        public void Transfer(Address to, ulong amount)
        {
            var from = Api.GetTransaction().From;

            DoTransfer(from, to, amount);
        }