public PoaConsensusTests(ITestOutputHelper output) : base(output)
        {
            ContainerProvider.ConfigureContainerBuilder(true, true, true);
            _scope = ContainerProvider.Container.BeginLifetimeScope(CurrentTestName);

            var context = new FfiWrapper();

            _endOfTestCancellationSource = new CancellationTokenSource();

            var poaNodeDetails = Enumerable.Range(0, 3).Select(i =>
            {
                var privateKey     = context.GeneratePrivateKey();
                var publicKey      = privateKey.GetPublicKey();
                var nodeSettings   = PeerSettingsHelper.TestPeerSettings(publicKey.Bytes, 2000 + i);
                var peerIdentifier = nodeSettings.PeerId;
                var name           = $"producer{i.ToString()}";
                return(new { index = i, name, privateKey, nodeSettings, peerIdentifier });
            }
                                                               ).ToList();

            var peerIdentifiers = poaNodeDetails.Select(n => n.peerIdentifier).ToList();

            _nodes = poaNodeDetails.Select(
                p => new PoaTestNode($"producer{p.index.ToString()}",
                                     p.privateKey,
                                     p.nodeSettings,
                                     peerIdentifiers.Except(new[] { p.peerIdentifier }),
                                     FileSystem,
                                     output)).ToList();
        }
        public void ValidateTransactionSignature_will_pass_with_valid_transaction_signature()
        {
            var subbedLogger         = Substitute.For <ILogger>();
            var cryptoContext        = new FfiWrapper();
            var transactionValidator = new TransactionValidator(subbedLogger, cryptoContext);

            // build a valid transaction
            var privateKey = cryptoContext.GeneratePrivateKey();

            var validTransaction = new PublicEntry
            {
                SenderAddress = privateKey.GetPublicKey().Bytes.ToByteString()
            };

            var signingContext = new SigningContext
            {
                NetworkType   = NetworkType.Devnet,
                SignatureType = SignatureType.TransactionPublic
            };

            var signature = new Signature
            {
                // sign an actual TransactionBroadcast object
                RawBytes = cryptoContext.Sign(privateKey, validTransaction.ToByteArray(), signingContext.ToByteArray())
                           .SignatureBytes.ToByteString(),
                SigningContext = signingContext
            };

            validTransaction.Signature = signature;

            var result = transactionValidator.ValidateTransaction(validTransaction);

            result.Should().BeTrue();
        }
示例#3
0
        public static readonly string TestPublicKey; // = "qnb9bw3b2yj4hpjcmsvgp12bkwff313v9gaqb18atvwfpevrmmf0"

        static TestKeyRegistry()
        {
            var cryptoContext  = new FfiWrapper();
            var fakePrivateKey = cryptoContext.GetPrivateKeyFromBytes(TestPrivateKey.KeyToBytes());

            TestPublicKey = fakePrivateKey.GetPublicKey().Bytes.KeyToString();
        }
示例#4
0
        public static BroadcastRawTransactionRequest GenerateTransaction(uint amount, int fee, int nonce = 0)
        {
            var cryptoWrapper = new FfiWrapper();
            var privateKey    = cryptoWrapper.GeneratePrivateKey();
            var publicKey     = ByteString.CopyFrom(privateKey.GetPublicKey().Bytes);

            var transaction = new TransactionBroadcast
            {
                PublicEntry = new PublicEntry
                {
                    Amount          = ((UInt256)amount).ToUint256ByteString(),
                    Nonce           = (ulong)nonce,
                    SenderAddress   = privateKey.GetPublicKey().Bytes.ToByteString(),
                    ReceiverAddress = publicKey,
                    TransactionFees = ((UInt256)fee).ToUint256ByteString(),
                    Timestamp       = Timestamp.FromDateTime(DateTime.UtcNow)
                }.Sign(cryptoWrapper, privateKey, DevNetPublicTransactionContext)
            };

            var broadcastRawTransactionRequest = new BroadcastRawTransactionRequest
            {
                Transaction = transaction
            };

            return(broadcastRawTransactionRequest);
        }
示例#5
0
        public SimpleRpcClient(IUserOutput userOutput,
                               IPasswordRegistry passwordRegistry,
                               X509Certificate2 certificate,
                               ILogger logger,
                               SigningContext signingContextProvider)
        {
            _logger      = logger;
            _certificate = certificate;

            var fileSystem = new FileSystem();

            var consolePasswordReader = new ConsolePasswordReader(userOutput, new ConsoleUserInput());
            var passwordManager       = new PasswordManager(consolePasswordReader, passwordRegistry);

            var cryptoContext = new FfiWrapper();

            var hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));

            var peerSettings = Substitute.For <IPeerSettings>();

            peerSettings.NetworkType.Returns(signingContextProvider.NetworkType);

            var localKeyStore = new LocalKeyStore(passwordManager, cryptoContext, fileSystem, hashProvider, _logger);

            var keyRegistry = new KeyRegistry();
            var keySigner   = new KeySigner(localKeyStore, cryptoContext, keyRegistry);

            var memoryCacheOptions        = new MemoryCacheOptions();
            var memoryCache               = new MemoryCache(memoryCacheOptions);
            var changeTokenProvider       = new TtlChangeTokenProvider(10000);
            var messageCorrelationManager = new RpcMessageCorrelationManager(memoryCache, _logger, changeTokenProvider);
            var peerIdValidator           = new PeerIdValidator(cryptoContext);

            var nodeRpcClientChannelFactory =
                new RpcClientChannelFactory(keySigner, messageCorrelationManager, peerIdValidator, peerSettings);

            var eventLoopGroupFactoryConfiguration = new EventLoopGroupFactoryConfiguration
            {
                TcpClientHandlerWorkerThreads = 4
            };

            var tcpClientEventLoopGroupFactory = new TcpClientEventLoopGroupFactory(eventLoopGroupFactoryConfiguration);

            var handlers = new List <IRpcResponseObserver>
            {
                new BroadcastRawTransactionResponseObserver(_logger),
                new GetVersionResponseObserver(_logger)
            };

            _rpcClientFactory =
                new RpcClientFactory(nodeRpcClientChannelFactory, tcpClientEventLoopGroupFactory, handlers);

            //PeerId for RPC/TCP is currently redundant.
            var publicKey = keyRegistry.GetItemFromRegistry(KeyRegistryTypes.DefaultKey).GetPublicKey().Bytes;

            _senderPeerId = publicKey.BuildPeerIdFromPublicKey(IPAddress.Any, 1026);
        }
示例#6
0
        private byte[] PrepareEd25519PrecompileCall(HashProvider hashProvider, FfiWrapper cryptoContext, IPrivateKey signingPrivateKey, IPrivateKey otherPrivateKey)
        {
            var data    = Encoding.UTF8.GetBytes("Testing testing 1 2 3");
            var message = hashProvider.ComputeMultiHash(data).Digest;

            var signingContext = Encoding.UTF8.GetBytes("Testing testing 1 2 3 context");
            var context        = hashProvider.ComputeMultiHash(signingContext).Digest;

            ISignature signature      = cryptoContext.Sign(signingPrivateKey, message, context);
            var        signatureBytes = signature.SignatureBytes;
            var        publicKeyBytes = otherPrivateKey.GetPublicKey().Bytes;

            // below verify check is not needed but allows for greater confidence for any person in the future
            // that would approach and debug test when it goes wrong
            // =====================================================
            cryptoContext.Verify(signature, message, context)
            .Should().BeTrue("signature generated with private key should verify with corresponding public key");

            // =====================================================

            // save message hash in memory at position 0x00
            string pushToMemoryAt0 = "7f" + message.ToHexString(false) + "600052";

            // save first 32 bytes of the sig in memory starting from position 0x20
            string pushToMemoryAt32 = "7f" + signatureBytes.AsSpan(0, 32).ToHexString(false) + "602052";

            // save remaining 32 bytes of the sig in memory starting from position 0x40
            string pushToMemoryAt64 = "7f" + signatureBytes.AsSpan(32, 32).ToHexString(false) + "604052";

            // save context bytes in memory starting from position 0x60 (but this should be changed if context is smaller)
            string pushToMemoryAt96 = "7f" + context.ToHexString(false) + "606052";

            // save public key bytes in memory starting from position 0x80 (but this should be changed if context is smaller)
            string pushToMemoryAt128 = "7f" + publicKeyBytes.ToHexString(false) + "608052";

            // address of the precompile within Catalyst
            string addressCode = GetEd25519PrecompileAddressAsHex();

            var byteCode = Bytes.FromHexString(
                pushToMemoryAt0 +
                pushToMemoryAt32 +
                pushToMemoryAt64 +
                pushToMemoryAt96 +
                pushToMemoryAt128 +

                // PUSH1 32 PUSH1 0 PUSH1 160 PUSH1 0 PUSH20 address GAS STATICCALL
                // make a call to precompile and pass [0,160) bytes of memory as an input
                // and store result at [0,1) of memory array
                // allow precompile to use all the gas required
                "6001600060a0600073" +
                addressCode +
                "45fa00");

            TestContext.WriteLine(byteCode.ToHexString());
            return(byteCode);
        }
示例#7
0
        public void Can_Encode_And_Decode_Correctly()
        {
            var cryptoContext = new FfiWrapper();
            var privateKey    = cryptoContext.GeneratePrivateKey();
            var publicKey     = privateKey.GetPublicKey();

            var publicKeyAfterEncodeDecode = publicKey.Bytes.KeyToString().KeyToBytes();

            publicKeyAfterEncodeDecode.Should().BeEquivalentTo(publicKey.Bytes);
        }
示例#8
0
        public static IKeyRegistry MockKeyRegistry()
        {
            var keyRegistry    = Substitute.For <IKeyRegistry>();
            var cryptoContext  = new FfiWrapper();
            var fakePrivateKey = cryptoContext.GetPrivateKeyFromBytes(TestPrivateKey.KeyToBytes());

            keyRegistry.GetItemFromRegistry(KeyRegistryTypes.DefaultKey).Returns(fakePrivateKey);
            keyRegistry.Contains(Arg.Any <byte[]>()).Returns(true);
            return(keyRegistry);
        }
示例#9
0
        public void Ed25519_precompile_can_verify_correct_sig()
        {
            HashProvider hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            FfiWrapper  cryptoContext         = new FfiWrapper();
            IPrivateKey signingPrivateKey     = cryptoContext.GeneratePrivateKey();
            var         signingPublicKeyBytes = signingPrivateKey.GetPublicKey().Bytes;

            var byteCode = PrepareEd25519PrecompileCall(hashProvider, cryptoContext, signingPrivateKey, signingPrivateKey);

            GethLikeTxTracer       txTracer   = RunVirtualMachine(byteCode);
            EthereumJsonSerializer serializer = new EthereumJsonSerializer();
            GethLikeTxTrace        trace      = txTracer.BuildResult();

            TestContext.WriteLine(serializer.Serialize(trace, true));
            trace.Entries.Last().Stack.First().Should().Be("0000000000000000000000000000000000000000000000000000000000000001");
            trace.Entries.Last().Memory.First().Should().StartWith("01");
        }
示例#10
0
        public void Init()
        {
            this.Setup(TestContext.CurrentContext);

            ContainerProvider.ConfigureContainerBuilder(true, true, true);

            var context = new FfiWrapper();

            _endOfTestCancellationSource = new CancellationTokenSource();

            var poaNodeDetails = Enumerable.Range(0, 3).Select(i =>
            {
                var fileSystem = Substitute.For <IFileSystem>();
                var path       = Path.Combine(FileSystem.GetCatalystDataDir().FullName, $"producer{i}");
                fileSystem.GetCatalystDataDir().Returns(new DirectoryInfo(path));

                var privateKey     = context.GeneratePrivateKey();
                var publicKey      = privateKey.GetPublicKey();
                var nodeSettings   = PeerSettingsHelper.TestPeerSettings(publicKey.Bytes, 2000 + i);
                var peerIdentifier = nodeSettings.PeerId;
                var name           = $"producer{i.ToString()}";
                var dfs            = TestDfs.GetTestDfs(fileSystem);
                return(new { index = i, name, privateKey, nodeSettings, peerIdentifier, dfs, fileSystem });
            }
                                                               ).ToList();

            var peerIdentifiers = poaNodeDetails.Select(n => n.peerIdentifier).ToList();

            _nodes = new List <PoaTestNode>();
            foreach (var nodeDetails in poaNodeDetails)
            {
                nodeDetails.dfs.Options.Discovery.BootstrapPeers = poaNodeDetails.Select(x => x.dfs.LocalPeer.Addresses.First());
                var node = new PoaTestNode(nodeDetails.name,
                                           nodeDetails.privateKey,
                                           nodeDetails.nodeSettings,
                                           nodeDetails.dfs,
                                           peerIdentifiers.Except(new[] { nodeDetails.peerIdentifier }),
                                           nodeDetails.fileSystem);

                _nodes.Add(node);
            }
        }
        public KeySignerIntegrationTests(ITestOutputHelper output) : base(output)
        {
            var logger = Substitute.For <ILogger>();

            var passwordManager = Substitute.For <IPasswordManager>();

            var cryptoContext = new FfiWrapper();

            var peerSettings = Substitute.For <IPeerSettings>();

            peerSettings.NetworkType.Returns(NetworkType.Devnet);

            var hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256"));

            var keystore = new LocalKeyStore(passwordManager, cryptoContext, FileSystem, hashProvider, peerSettings,
                                             logger);

            var keyRegistry = new KeyRegistry();

            _keySigner = new KeySigner(keystore, cryptoContext, keyRegistry);
        }
示例#12
0
        public void Init()
        {
            this.Setup(TestContext.CurrentContext);

            var logger = Substitute.For <ILogger>();

            var passwordManager = Substitute.For <IPasswordManager>();

            var cryptoContext = new FfiWrapper();

            var peerSettings = Substitute.For <IPeerSettings>();

            peerSettings.NetworkType.Returns(NetworkType.Devnet);

            var hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("keccak-256"));

            var keystore = new LocalKeyStore(passwordManager, cryptoContext, FileSystem, hashProvider,
                                             logger);

            var keyRegistry = new KeyRegistry();

            _keySigner = new KeySigner(keystore, cryptoContext, keyRegistry);
        }
示例#13
0
 public CryptoWrapperTests() { _wrapper = new FfiWrapper(); }
示例#14
0
 public CryptographyTests()
 {
     _context = new FfiWrapper();
 }