Exemplo n.º 1
0
 public SmartContractFeature(IConsensusManager consensusLoop, ILoggerFactory loggerFactory, Network network, IStateRepositoryRoot stateRoot)
 {
     this.consensusManager = consensusLoop;
     this.logger           = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode");
     this.network          = network;
     this.stateRoot        = stateRoot;
 }
 public SmartContractFeature(IConsensusManager consensusLoop, ILoggerFactory loggerFactory, Network network, IStateRepositoryRoot stateRoot)
 {
     this.consensusManager = consensusLoop;
     this.logger           = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network          = network;
     this.stateRoot        = stateRoot;
 }
        public Unity3dController(ILoggerFactory loggerFactory, IAddressIndexer addressIndexer,
                                 IBlockStore blockStore, IChainState chainState, Network network, ICoinView coinView, WalletController walletController, ChainIndexer chainIndexer, INFTTransferIndexer NFTTransferIndexer,
                                 IStakeChain stakeChain = null,
                                 IContractPrimitiveSerializer primitiveSerializer = null, IStateRepositoryRoot stateRoot = null, IContractAssemblyCache contractAssemblyCache                   = null,
                                 IReceiptRepository receiptRepository             = null, ISmartContractTransactionService smartContractTransactionService = null, ILocalExecutor localExecutor = null)
        {
            Guard.NotNull(loggerFactory, nameof(loggerFactory));
            this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
            this.addressIndexer     = Guard.NotNull(addressIndexer, nameof(addressIndexer));
            this.blockStore         = Guard.NotNull(blockStore, nameof(blockStore));
            this.chainState         = Guard.NotNull(chainState, nameof(chainState));
            this.network            = Guard.NotNull(network, nameof(network));
            this.coinView           = Guard.NotNull(coinView, nameof(coinView));
            this.walletController   = Guard.NotNull(walletController, nameof(walletController));
            this.chainIndexer       = Guard.NotNull(chainIndexer, nameof(chainIndexer));
            this.stakeChain         = stakeChain;
            this.NFTTransferIndexer = NFTTransferIndexer;

            this.primitiveSerializer             = primitiveSerializer;
            this.stateRoot                       = stateRoot;
            this.contractAssemblyCache           = contractAssemblyCache;
            this.receiptRepository               = receiptRepository;
            this.smartContractTransactionService = smartContractTransactionService;
            this.localExecutor                   = localExecutor;
        }
        public void EnrichLogs(Receipt receipt, List <LogResponse> logResponses)
        {
            if (!receipt.Success)
            {
                return;
            }

            // this is the constructor we want to fetch the name, symbol, decimals and total supply.
            IStateRepositoryRoot stateAtHeight = this.stateRoot.GetSnapshotTo(receipt.PostState.ToBytes());

            uint160 addressNumeric = receipt.MethodName != null || receipt.NewContractAddress == null ? receipt.To: receipt.NewContractAddress;

            byte[] owner             = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Owner"));
            byte[] whiteListCount    = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("WhitelistedCount"));
            byte[] minVotingDuration = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("MinVotingDuration"));
            byte[] maxVotingDuration = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("MaxVotingDuration"));
            byte[] lastProposalId    = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("LastProposalId"));



            logResponses.Add(new LogResponse(new Log(addressNumeric, new List <byte[]>(), new byte[0]), this.network)
            {
                Log = new LogData("Constructor", new Dictionary <string, object>
                {
                    { "Owner", serializer.ToAddress(owner).ToUint160().ToBase58Address(this.network) },
                    { "WhitelistedCount", whiteListCount == null ? 0 : serializer.ToUInt32(whiteListCount) },
                    { "MinVotingDuration", serializer.ToUInt32(minVotingDuration) },
                    { "MaxVotingDuration", serializer.ToUInt32(maxVotingDuration) },
                    { "LastProposalId", serializer.ToUInt32(lastProposalId) },
                })
            });
        }
Exemplo n.º 5
0
        public void EnrichLogs(Receipt receipt, List <LogResponse> logResponses)
        {
            if (!receipt.Success)
            {
                return;
            }
            if (receipt.MethodName != null || receipt.NewContractAddress == null)
            {
                return;
            }

            // this is the constructor we want to fetch the name, symbol, decimals and total supply.
            IStateRepositoryRoot stateAtHeight = this.stateRoot.GetSnapshotTo(receipt.PostState.ToBytes());

            uint160 addressNumeric = receipt.NewContractAddress;

            byte[] tokenName        = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Name"));
            byte[] tokenSymbole     = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Symbol"));
            byte[] tokenTotalSupply = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("TotalSupply"));
            byte[] tokenDecimals    = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Decimals"));

            logResponses.Add(new LogResponse(new Log(addressNumeric, new List <byte[]>(), new byte[0]), this.network)
            {
                Log = new LogData("Constructor", new Dictionary <string, object>
                {
                    { "tokenName", serializer.ToString(tokenName) },
                    { "tokenSymbole", serializer.ToString(tokenSymbole) },
                    { "tokenTotalSupply", serializer.ToInt64(tokenTotalSupply) },
                    { "tokenDecimals", tokenDecimals?[0] }
                })
            });
        }
Exemplo n.º 6
0
 public NonFungibleTokenLogEnrichment(IStateRepositoryRoot stateRoot, Network network, ISerializer serializer, ILoggerFactory loggerFactory)
 {
     this.stateRoot  = stateRoot;
     this.network    = network;
     this.serializer = serializer;
     logger          = loggerFactory.CreateLogger(this.GetType().FullName);
 }
 public SmartContractPowConsensusRuleEngine(
     ICallDataSerializer callDataSerializer,
     ConcurrentChain chain,
     ICheckpoints checkpoints,
     ConsensusSettings consensusSettings,
     IDateTimeProvider dateTimeProvider,
     IContractExecutorFactory executorFactory,
     ILoggerFactory loggerFactory,
     Network network,
     NodeDeployments nodeDeployments,
     IStateRepositoryRoot originalStateRoot,
     IReceiptRepository receiptRepository,
     ISenderRetriever senderRetriever,
     ICoinView utxoSet,
     IChainState chainState,
     IInvalidBlockHashStore invalidBlockHashStore,
     INodeStats nodeStats)
     : base(network, loggerFactory, dateTimeProvider, chain, nodeDeployments, consensusSettings, checkpoints, utxoSet, chainState, invalidBlockHashStore, nodeStats)
 {
     this.CallDataSerializer = callDataSerializer;
     this.ExecutorFactory    = executorFactory;
     this.OriginalStateRoot  = originalStateRoot;
     this.ReceiptRepository  = receiptRepository;
     this.SenderRetriever    = senderRetriever;
 }
Exemplo n.º 8
0
 public ApiLogDeserializer(IContractPrimitiveSerializer primitiveSerializer, Network network, IStateRepositoryRoot stateRepositoryRoot, IContractAssemblyCache contractAssemblyCache)
 {
     this.primitiveSerializer   = primitiveSerializer;
     this.network               = network;
     this.stateRepositoryRoot   = stateRepositoryRoot;
     this.contractAssemblyCache = contractAssemblyCache;
 }
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStore blockStore,
                                 ChainIndexer chainIndexer,
                                 CSharpContractDecompiler contractDecompiler,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 ISerializer serializer,
                                 IContractPrimitiveSerializer primitiveSerializer,
                                 IReceiptRepository receiptRepository,
                                 ILocalExecutor localExecutor,
                                 ISmartContractTransactionService smartContractTransactionService,
                                 IConnectionManager connectionManager)
 {
     this.stateRoot                       = stateRoot;
     this.contractDecompiler              = contractDecompiler;
     this.logger                          = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network                         = network;
     this.chainIndexer                    = chainIndexer;
     this.blockStore                      = blockStore;
     this.walletManager                   = walletManager;
     this.broadcasterManager              = broadcasterManager;
     this.serializer                      = serializer;
     this.primitiveSerializer             = primitiveSerializer;
     this.receiptRepository               = receiptRepository;
     this.localExecutor                   = localExecutor;
     this.smartContractTransactionService = smartContractTransactionService;
     this.connectionManager               = connectionManager;
 }
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStore blockStore,
                                 ConcurrentChain chain,
                                 CSharpContractDecompiler contractDecompiler,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 ISerializer serializer,
                                 IReceiptRepository receiptRepository,
                                 ILocalExecutor localExecutor,
                                 ISmartContractTransactionService smartContractTransactionService)
 {
     this.stateRoot          = stateRoot;
     this.contractDecompiler = contractDecompiler;
     this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network            = network;
     this.chain              = chain;
     this.blockStore         = blockStore;
     this.walletManager      = walletManager;
     this.broadcasterManager = broadcasterManager;
     this.serializer         = serializer;
     this.receiptRepository  = receiptRepository;
     this.localExecutor      = localExecutor;
     this.smartContractTransactionService = smartContractTransactionService;
 }
        public async Task RunAsync(Func <RuleContext, Task> baseRunAsync, RuleContext context)
        {
            this.blockTxsProcessed.Clear();
            this.receipts.Clear();
            this.refundCounter = 1;
            Block block = context.ValidationContext.BlockToValidate;

            // Get a IStateRepositoryRoot we can alter without affecting the injected one which is used elsewhere.
            byte[] blockRoot = ((ISmartContractBlockHeader)context.ValidationContext.ChainedHeaderToValidate.Previous.Header).HashStateRoot.ToBytes();
            this.mutableStateRepository = this.ContractCoinviewRule.OriginalStateRoot.GetSnapshotTo(blockRoot);

            await baseRunAsync(context);

            var blockHeader = (ISmartContractBlockHeader)block.Header;

            if (new uint256(this.mutableStateRepository.Root) != blockHeader.HashStateRoot)
            {
                SmartContractConsensusErrors.UnequalStateRoots.Throw();
            }

            ValidateAndStoreReceipts(blockHeader.ReceiptRoot);
            ValidateLogsBloom(blockHeader.LogsBloom);

            // Push to underlying database
            this.mutableStateRepository.Commit();

            // Update the globally injected state so all services receive the updates.
            this.ContractCoinviewRule.OriginalStateRoot.SyncToRoot(this.mutableStateRepository.Root);
        }
Exemplo n.º 12
0
        public SmartContractBlockDefinition(
            IBlockBufferGenerator blockBufferGenerator,
            ICoinView coinView,
            IConsensusManager consensusManager,
            IDateTimeProvider dateTimeProvider,
            IContractExecutorFactory executorFactory,
            ILoggerFactory loggerFactory,
            ITxMempool mempool,
            MempoolSchedulerLock mempoolLock,
            MinerSettings minerSettings,
            Network network,
            ISenderRetriever senderRetriever,
            IStateRepositoryRoot stateRoot)
            : base(consensusManager, dateTimeProvider, loggerFactory, mempool, mempoolLock, minerSettings, network)
        {
            this.coinView        = coinView;
            this.executorFactory = executorFactory;
            this.logger          = loggerFactory.CreateLogger(this.GetType());
            this.senderRetriever = senderRetriever;
            this.stateRoot       = stateRoot;
            this.refundOutputs   = new List <TxOut>();
            this.receipts        = new List <Receipt>();

            // When building smart contract blocks, we will be generating and adding both transactions to the block and txouts to the coinbase.
            // At the moment, these generated objects aren't accounted for in the block size and weight accounting.
            // This means that if blocks started getting full, this miner could start generating blocks greater than the max consensus block size.
            // To avoid this without significantly overhauling the BlockDefinition, for now we just lower the block size by a percentage buffer.
            // If in the future blocks are being built over the size limit and you need an easy fix, just increase the size of this buffer.
            this.Options = blockBufferGenerator.GetOptionsWithBuffer(this.Options);
        }
        public void Repository_CacheDoesntCarryOver()
        {
            const string             testContractType = "A String";
            ISource <byte[], byte[]> stateDB          = new NoDeleteSource <byte[], byte[]>(new MemoryDictionarySource());
            StateRepositoryRoot      repository       = new StateRepositoryRoot(stateDB);

            byte[] initialRoot = repository.Root;

            IStateRepository txTrack = repository.StartTracking();

            txTrack.CreateAccount(testAddress);
            txTrack.SetStorageValue(testAddress, dog, cat);
            txTrack.SetContractType(testAddress, testContractType);
            txTrack.Commit();
            repository.Commit();

            byte[] postChangesRoot = repository.Root;

            IStateRepositoryRoot repository2 = repository.GetSnapshotTo(initialRoot);

            Assert.Null(repository2.GetAccountState(testAddress));
            repository2.SetContractType(testAddress, "Something Else");
            repository2.SyncToRoot(postChangesRoot);
            Assert.Equal(testContractType, repository2.GetContractType(testAddress));
        }
Exemplo n.º 14
0
        public SmartContractTransactionService(
            Network network,
            IWalletManager walletManager,
            IWalletTransactionHandler walletTransactionHandler,
            IMethodParameterStringSerializer methodParameterStringSerializer,
            ICallDataSerializer callDataSerializer,
            IAddressGenerator addressGenerator,
            IStateRepositoryRoot stateRoot,
            IReserveUtxoService reserveUtxoService,
            IBlockStore blockStore,
            ChainIndexer chainIndexer,
            IContractPrimitiveSerializer primitiveSerializer,
            IContractAssemblyCache contractAssemblyCache,
            IReceiptRepository receiptRepository
            )
        {
            this.network                         = network;
            this.walletManager                   = walletManager;
            this.walletTransactionHandler        = walletTransactionHandler;
            this.methodParameterStringSerializer = methodParameterStringSerializer;
            this.callDataSerializer              = callDataSerializer;
            this.addressGenerator                = addressGenerator;
            this.stateRoot                       = stateRoot;
            this.reserveUtxoService              = reserveUtxoService;

            this.blockStore            = blockStore;
            this.chainIndexer          = chainIndexer;
            this.primitiveSerializer   = primitiveSerializer;
            this.contractAssemblyCache = contractAssemblyCache;
            this.receiptRepository     = receiptRepository;
        }
        /// <inheritdoc/>
        public override BlockTemplate Build(ChainedHeader chainTip, Script scriptPubKeyIn)
        {
            this.logger.LogTrace("()");

            GetSenderResult getSenderResult = this.senderRetriever.GetAddressFromScript(scriptPubKeyIn);

            if (!getSenderResult.Success)
            {
                throw new ConsensusErrorException(new ConsensusError("sc-block-assembler-createnewblock", getSenderResult.Error));
            }

            this.coinbaseAddress = getSenderResult.Sender;

            this.stateSnapshot = this.stateRoot.GetSnapshotTo(((SmartContractBlockHeader)this.ConsensusManager.Tip.Header).HashStateRoot.ToBytes());

            this.refundOutputs.Clear();
            this.receipts.Clear();

            base.OnBuild(chainTip, scriptPubKeyIn);

            this.coinbase.Outputs.AddRange(this.refundOutputs);

            this.logger.LogTrace("(-)");

            return(this.BlockTemplate);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Initialize a smart contract executor for the block assembler or consensus validator.
 /// <para>
 /// After the contract has been executed, it will process any fees and/or refunds.
 /// </para>
 /// </summary>
 public IContractExecutor CreateExecutor(
     IStateRepositoryRoot stateRepository,
     IContractTransactionContext transactionContext)
 {
     return(new ContractExecutor(this.loggerFactory, this.serializer,
                                 stateRepository, this.refundProcessor, this.transferProcessor, this.network, this.stateFactory, this.stateProcessor, this.contractPrimitiveSerializer));
 }
Exemplo n.º 17
0
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStore blockStore,
                                 ConcurrentChain chain,
                                 IConsensusManager consensus,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 IWalletTransactionHandler walletTransactionHandler,
                                 IAddressGenerator addressGenerator,
                                 ISerializer serializer,
                                 IReceiptRepository receiptRepository,
                                 ICallDataSerializer callDataSerializer,
                                 IMethodParameterStringSerializer methodParameterStringSerializer,
                                 ILocalExecutor localExecutor)
 {
     this.stateRoot = stateRoot;
     this.walletTransactionHandler = walletTransactionHandler;
     this.logger             = loggerFactory.CreateLogger(this.GetType().FullName);
     this.network            = network;
     this.coinType           = (CoinType)network.Consensus.CoinType;
     this.chain              = chain;
     this.blockStore         = blockStore;
     this.walletManager      = walletManager;
     this.broadcasterManager = broadcasterManager;
     this.addressGenerator   = addressGenerator;
     this.serializer         = serializer;
     this.receiptRepository  = receiptRepository;
     this.callDataSerializer = callDataSerializer;
     this.methodParameterStringSerializer = methodParameterStringSerializer;
     this.localExecutor = localExecutor;
 }
Exemplo n.º 18
0
        private void AddCreateDataToLog(Receipt receipt, List <LogResponse> logResponses)
        {
            if (receipt.MethodName != null || receipt.NewContractAddress == null)
            {
                return;
            }

            // this is the constructor we want to fetch the name, symbol, decimals and total supply.
            IStateRepositoryRoot stateAtHeight = stateRoot.GetSnapshotTo(receipt.PostState.ToBytes());

            uint160 addressNumeric = receipt.NewContractAddress;

            byte[] nftName             = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Name"));
            byte[] nftSymbole          = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Symbol"));
            byte[] nftOwner            = stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("Owner"));
            byte[] nftOwnerOnlyMinting =
                stateAtHeight.GetStorageValue(addressNumeric, Encoding.UTF8.GetBytes("OwnerOnlyMinting"));

            logResponses.Add(new LogResponse(new Log(addressNumeric, new List <byte[]>(), new byte[0]), this.network)
            {
                Log = new LogData("Constructor", new Dictionary <string, object>
                {
                    { "nftName", serializer.ToString(nftName) },
                    { "nftSymbol", serializer.ToString(nftSymbole) },
                    { "nftOwner", serializer.ToAddress(nftOwner).ToUint160().ToBase58Address(this.network) },
                    { "nftOwnerOnlyMinting", serializer.ToBool(nftOwnerOnlyMinting) }
                })
            });
        }
        /// <inheritdoc />
        public override async Task RunAsync(RuleContext context)
        {
            this.blockTxsProcessed = new List <Transaction>();
            this.receipts          = new List <Receipt>();
            this.refundCounter     = 1;
            NBitcoin.Block block = context.ValidationContext.BlockToValidate;

            // Get a IStateRepositoryRoot we can alter without affecting the injected one which is used elsewhere.
            byte[] blockRoot = ((SmartContractBlockHeader)context.ValidationContext.ChainedHeaderToValidate.Previous.Header).HashStateRoot.ToBytes();
            this.mutableStateRepository = this.ContractCoinviewRule.OriginalStateRoot.GetSnapshotTo(blockRoot);

            await base.RunAsync(context);

            if (new uint256(this.mutableStateRepository.Root) != ((SmartContractBlockHeader)block.Header).HashStateRoot)
            {
                SmartContractConsensusErrors.UnequalStateRoots.Throw();
            }

            ValidateAndStoreReceipts(((SmartContractBlockHeader)block.Header).ReceiptRoot);

            // Push to underlying database
            this.mutableStateRepository.Commit();

            // Update the globally injected state so all services receive the updates.
            this.ContractCoinviewRule.OriginalStateRoot.SyncToRoot(this.mutableStateRepository.Root);
        }
Exemplo n.º 20
0
 public SmartContractsController(IBroadcasterManager broadcasterManager,
                                 IBlockStore blockStore,
                                 ChainIndexer chainIndexer,
                                 CSharpContractDecompiler contractDecompiler,
                                 IDateTimeProvider dateTimeProvider,
                                 ILoggerFactory loggerFactory,
                                 Network network,
                                 IStateRepositoryRoot stateRoot,
                                 IWalletManager walletManager,
                                 ISerializer serializer,
                                 IReceiptRepository receiptRepository,
                                 ILocalExecutor localExecutor,
                                 ISmartContractTransactionService smartContractTransactionService,
                                 IConnectionManager connectionManager)
 {
     this.stateRoot          = stateRoot;
     this.contractDecompiler = contractDecompiler;
     this.logger             = loggerFactory.CreateLogger("Impleum.Bitcoin.Fullnode");
     this.network            = network;
     this.chainIndexer       = chainIndexer;
     this.blockStore         = blockStore;
     this.walletManager      = walletManager;
     this.broadcasterManager = broadcasterManager;
     this.serializer         = serializer;
     this.receiptRepository  = receiptRepository;
     this.localExecutor      = localExecutor;
     this.smartContractTransactionService = smartContractTransactionService;
     this.connectionManager = connectionManager;
 }
Exemplo n.º 21
0
        public async Task RunAsync(Func <RuleContext, Task> baseRunAsync, RuleContext context)
        {
            this.blockTxsProcessed.Clear();
            this.receipts.Clear();
            this.blockGasConsumed = 0;
            this.refundCounter    = 1;

            Block block = context.ValidationContext.BlockToValidate;

            this.logger.LogDebug("Block to validate '{0}'", block.GetHash());

            // Get a IStateRepositoryRoot we can alter without affecting the injected one which is used elsewhere.
            uint256 blockRoot = ((ISmartContractBlockHeader)context.ValidationContext.ChainedHeaderToValidate.Previous.Header).HashStateRoot;

            this.logger.LogDebug("Block hash state root '{0}'.", blockRoot);

            this.cachedResults = this.executionCache.GetExecutionResult(block.GetHash());

            if (this.cachedResults == null)
            {
                // We have no cached results. Didn't come from our miner. We execute the contracts, so need to set up a new state repository.
                this.mutableStateRepository = this.stateRepositoryRoot.GetSnapshotTo(blockRoot.ToBytes());
            }
            else
            {
                // We have already done all of this execution when mining so we will use those results.
                this.mutableStateRepository = this.cachedResults.MutatedStateRepository;

                foreach (Receipt receipt in this.cachedResults.Receipts)
                {
                    // Block hash needs to be set for all. It was set during mining and can only be updated after.
                    receipt.BlockHash = block.GetHash();
                    this.receipts.Add(receipt);
                }
            }

            // Always call into the base. When the base class calls back in, we will optionally perform execution based on whether this.cachedResults is set.
            await baseRunAsync(context);

            var blockHeader = (ISmartContractBlockHeader)block.Header;

            var     mutableStateRepositoryRoot = new uint256(this.mutableStateRepository.Root);
            uint256 blockHeaderHashStateRoot   = blockHeader.HashStateRoot;

            this.logger.LogDebug("Compare state roots '{0}' and '{1}'", mutableStateRepositoryRoot, blockHeaderHashStateRoot);
            if (mutableStateRepositoryRoot != blockHeaderHashStateRoot)
            {
                SmartContractConsensusErrors.UnequalStateRoots.Throw();
            }

            this.ValidateAndStoreReceipts(blockHeader.ReceiptRoot);
            this.ValidateLogsBloom(blockHeader.LogsBloom);

            // Push to underlying database
            this.mutableStateRepository.Commit();

            // Update the globally injected state so all services receive the updates.
            this.stateRepositoryRoot.SyncToRoot(this.mutableStateRepository.Root);
        }
Exemplo n.º 22
0
 public P2PKHNotContractMempoolRule(Network network,
                                    ITxMempool mempool,
                                    MempoolSettings mempoolSettings,
                                    ChainIndexer chainIndexer,
                                    IStateRepositoryRoot stateRepositoryRoot,
                                    ILoggerFactory loggerFactory) : base(network, mempool, mempoolSettings, chainIndexer, loggerFactory)
 {
     this.stateRepositoryRoot = stateRepositoryRoot;
 }
 public SmartContractCollateralPoARuleRegistration(Network network, IStateRepositoryRoot stateRepositoryRoot, IContractExecutorFactory executorFactory,
                                                   ICallDataSerializer callDataSerializer, ISenderRetriever senderRetriever, IReceiptRepository receiptRepository, ICoinView coinView,
                                                   IEnumerable <IContractTransactionPartialValidationRule> partialTxValidationRules, IEnumerable <IContractTransactionFullValidationRule> fullTxValidationRules,
                                                   IInitialBlockDownloadState ibdState, ISlotsManager slotsManager, ICollateralChecker collateralChecker)
     : base(network, stateRepositoryRoot, executorFactory, callDataSerializer, senderRetriever, receiptRepository, coinView, partialTxValidationRules, fullTxValidationRules)
 {
     this.ibdState          = ibdState;
     this.slotsManager      = slotsManager;
     this.collateralChecker = collateralChecker;
 }
Exemplo n.º 24
0
 public SmartContractPosCoinviewRule(Network network, IStateRepositoryRoot stateRepositoryRoot,
                                     IContractExecutorFactory executorFactory, ICallDataSerializer callDataSerializer,
                                     ISenderRetriever senderRetriever, IReceiptRepository receiptRepository, ICoinView coinView,
                                     IStakeChain stakeChain, IStakeValidator stakeValidator)
     : base(network, stateRepositoryRoot, executorFactory, callDataSerializer, senderRetriever, receiptRepository, coinView)
 {
     this.consensus      = network.Consensus;
     this.stakeChain     = stakeChain;
     this.stakeValidator = stakeValidator;
 }
Exemplo n.º 25
0
 /// <summary>
 /// Creates a new DynamicContractController instance.
 /// </summary>
 /// <param name="smartContractWalletController"></param>
 /// <param name="localCallController"></param>
 /// <param name="stateRoot"></param>
 /// <param name="loader"></param>
 /// <param name="network"></param>
 public DynamicContractController(
     SmartContractWalletController smartContractWalletController,
     SmartContractsController localCallController,
     IStateRepositoryRoot stateRoot,
     ILoader loader,
     Network network)
 {
     this.smartContractWalletController = smartContractWalletController;
     this.localCallController           = localCallController;
     this.stateRoot = stateRoot;
     this.loader    = loader;
     this.network   = network;
 }
Exemplo n.º 26
0
 public LocalExecutor(ILoggerFactory loggerFactory,
                      ICallDataSerializer serializer,
                      IStateRepositoryRoot stateRoot,
                      IStateFactory stateFactory,
                      IStateProcessor stateProcessor,
                      IContractPrimitiveSerializer contractPrimitiveSerializer)
 {
     this.logger         = loggerFactory.CreateLogger(this.GetType());
     this.stateRoot      = stateRoot;
     this.serializer     = serializer;
     this.stateFactory   = stateFactory;
     this.stateProcessor = stateProcessor;
     this.contractPrimitiveSerializer = contractPrimitiveSerializer;
 }
Exemplo n.º 27
0
 public static void CheckTransaction(IStateRepositoryRoot stateRepositoryRoot, Transaction transaction)
 {
     foreach (TxOut output in transaction.Outputs)
     {
         if (PayToPubkeyHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey))
         {
             KeyId p2pkhParams = PayToPubkeyHashTemplate.Instance.ExtractScriptPubKeyParameters(output.ScriptPubKey);
             var   to          = new uint160(p2pkhParams.ToBytes());
             if (stateRepositoryRoot.GetAccountState(to) != null)
             {
                 new ConsensusError("p2pkh-to-contract", "attempted send directly to contract address. use OP_CALL instead.").Throw();
             }
         }
     }
 }
 public ContractSwaggerController(
     SwaggerGeneratorOptions options,
     SwaggerUIOptions uiOptions,
     ILoader loader,
     IWalletManager walletmanager,
     IStateRepositoryRoot stateRepository,
     Network network)
 {
     this.options         = options;
     this.uiOptions       = uiOptions;
     this.loader          = loader;
     this.walletmanager   = walletmanager;
     this.stateRepository = stateRepository;
     this.network         = network;
 }
Exemplo n.º 29
0
 public SmartContractPoACoinviewRule(
     IStateRepositoryRoot stateRepositoryRoot,
     IContractExecutorFactory executorFactory,
     ICallDataSerializer callDataSerializer,
     ISenderRetriever senderRetriever,
     IReceiptRepository receiptRepository,
     ICoinView coinView)
 {
     this.stateRepositoryRoot = stateRepositoryRoot;
     this.executorFactory     = executorFactory;
     this.callDataSerializer  = callDataSerializer;
     this.senderRetriever     = senderRetriever;
     this.receiptRepository   = receiptRepository;
     this.coinView            = coinView;
 }
Exemplo n.º 30
0
        /// <summary>
        /// Create the wallet manager and wallet transaction handler.
        /// </summary>
        /// <param name="dataFolder">The data folder.</param>
        protected void Init(DataFolder dataFolder)
        {
            this.dataFolder = dataFolder;

            // Create the wallet manager.
            this.federationWalletManager = new FederationWalletManager(
                this.loggerFactory,
                this.network,
                this.ChainIndexer,
                dataFolder,
                this.walletFeePolicy,
                this.asyncProvider,
                new NodeLifetime(),
                this.dateTimeProvider,
                this.federatedPegSettings,
                this.withdrawalExtractor,
                this.blockRepository);

            // Starts and creates the wallet.
            this.federationWalletManager.Start();
            this.wallet = this.federationWalletManager.GetWallet();

            // TODO: The transaction builder, cross-chain store and fed wallet tx handler should be tested individually.
            this.FederationWalletTransactionHandler = new FederationWalletTransactionHandler(this.loggerFactory, this.federationWalletManager, this.walletFeePolicy, this.network, this.federatedPegSettings);
            this.stateRepositoryRoot          = Substitute.For <IStateRepositoryRoot>();
            this.withdrawalTransactionBuilder = new WithdrawalTransactionBuilder(this.loggerFactory, this.network, this.federationWalletManager, this.FederationWalletTransactionHandler, this.federatedPegSettings, this.signals);

            var storeSettings = (StoreSettings)FormatterServices.GetUninitializedObject(typeof(StoreSettings));

            this.federationWalletSyncManager = new FederationWalletSyncManager(this.loggerFactory, this.federationWalletManager, this.ChainIndexer, this.network,
                                                                               this.blockRepository, storeSettings, Substitute.For <INodeLifetime>(), this.asyncProvider);

            this.federationWalletSyncManager.Initialize();

            // Set up the encrypted seed on the wallet.
            string encryptedSeed = this.extendedKey.PrivateKey.GetEncryptedBitcoinSecret(walletPassword, this.network).ToWif();

            this.wallet.EncryptedSeed = encryptedSeed;

            this.federationWalletManager.Secret = new WalletSecret()
            {
                WalletPassword = walletPassword
            };

            FieldInfo isFederationActiveField = this.federationWalletManager.GetType().GetField("isFederationActive", BindingFlags.NonPublic | BindingFlags.Instance);

            isFederationActiveField.SetValue(this.federationWalletManager, true);
        }