public string?InitializeFromEncryptedSeed(string encryptedSeed, string pin)
        {
            byte[] seed;
            try
            {
                seed = DecryptEncryptedSeed(_hex.DecodeData(encryptedSeed), pin);
            }
            catch (NRustLightningException e)
            {
                return(e.Message);
            }

            InitializeFromSeed(seed);
            return(null);
        }
Example #2
0
        public uint160(string str)
        {
            pn0 = 0;
            pn1 = 0;
            pn2 = 0;
            pn3 = 0;
            pn4 = 0;
            str = str.Trim();

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                str = str.Substring(2);
            }

            var bytes = Encoder.DecodeData(str).Reverse().ToArray();

            if (bytes.Length != WIDTH_BYTE)
            {
                throw new FormatException("Invalid hex length");
            }
            pn0 = Utils.ToUInt32(bytes, 4 * 0, true);
            pn1 = Utils.ToUInt32(bytes, 4 * 1, true);
            pn2 = Utils.ToUInt32(bytes, 4 * 2, true);
            pn3 = Utils.ToUInt32(bytes, 4 * 3, true);
            pn4 = Utils.ToUInt32(bytes, 4 * 4, true);
        }
        /// <summary>
        /// Create a uint256 from a string in big endian
        /// </summary>
        /// <param name="str"></param>
        public uint256(string str)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
            if (str.Length != 64)
            {
                if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                {
                    str = str.Substring(2);
                }
                str = str.Trim();
                if (str.Length != 64)
                {
                    throw new FormatException("A uint256 must be 64 characters");
                }
            }

#if HAS_SPAN
            if (BitConverter.IsLittleEndian)
            {
                Span <byte> tmp = stackalloc byte[32];
                Encoder.DecodeData(str, tmp);
                tmp.Reverse();
                Span <ulong> uints = MemoryMarshal.Cast <byte, ulong>(tmp);
                pn0 = uints[0];
                pn1 = uints[1];
                pn2 = uints[2];
                pn3 = uints[3];
                return;
            }
#endif
            var bytes = Encoder.DecodeData(str);
            Array.Reverse(bytes);
            pn0 = Utils.ToUInt64(bytes, 8 * 0, true);
            pn1 = Utils.ToUInt64(bytes, 8 * 1, true);
            pn2 = Utils.ToUInt64(bytes, 8 * 2, true);
            pn3 = Utils.ToUInt64(bytes, 8 * 3, true);
        }
Example #4
0
        internal void SetHex(string str)
        {
            Array.Clear(pn, 0, pn.Length);
            str = str.Trim();

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                str = str.Substring(2);
            }

            var bytes = Encoder.DecodeData(str).Reverse().ToArray();

            SetBytes(bytes);
        }
Example #5
0
        public uint512(string str)
        {
            pn0  = 0;
            pn1  = 0;
            pn2  = 0;
            pn3  = 0;
            pn4  = 0;
            pn5  = 0;
            pn6  = 0;
            pn7  = 0;
            pn8  = 0;
            pn9  = 0;
            pn10 = 0;
            pn11 = 0;
            pn12 = 0;
            pn13 = 0;
            pn14 = 0;
            pn15 = 0;
            str  = str.Trim();

            if (str.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
            {
                str = str.Substring(2);
            }

            var bytes = Encoder.DecodeData(str).Reverse().ToArray();

            if (bytes.Length != WIDTH_BYTE)
            {
                throw new FormatException("Invalid hex length");
            }
            pn0  = Utils.ToUInt32(bytes, 4 * 0, true);
            pn1  = Utils.ToUInt32(bytes, 4 * 1, true);
            pn2  = Utils.ToUInt32(bytes, 4 * 2, true);
            pn3  = Utils.ToUInt32(bytes, 4 * 3, true);
            pn4  = Utils.ToUInt32(bytes, 4 * 4, true);
            pn5  = Utils.ToUInt32(bytes, 4 * 5, true);
            pn6  = Utils.ToUInt32(bytes, 4 * 6, true);
            pn7  = Utils.ToUInt32(bytes, 4 * 7, true);
            pn8  = Utils.ToUInt32(bytes, 4 * 8, true);
            pn9  = Utils.ToUInt32(bytes, 4 * 9, true);
            pn10 = Utils.ToUInt32(bytes, 4 * 10, true);
            pn11 = Utils.ToUInt32(bytes, 4 * 11, true);
            pn12 = Utils.ToUInt32(bytes, 4 * 12, true);
            pn13 = Utils.ToUInt32(bytes, 4 * 13, true);
            pn14 = Utils.ToUInt32(bytes, 4 * 14, true);
            pn15 = Utils.ToUInt32(bytes, 4 * 15, true);
        }
Example #6
0
 public static byte[] getOpReturnFullData(RestApiTransaction tx)
 {
     if (tx != null)
     {
         if (tx.Outputs != null)
         {
             string opReturnHexStr = null;
             foreach (RestApiOutput output in tx.Outputs)
             {
                 opReturnHexStr = output.ScriptPubKey.Hex;
                 if (opReturnHexStr.Substring(0, 4) == "006a" ||
                     opReturnHexStr.Substring(0, 2) == "6a")
                 {
                     HexEncoder hexEncoder = new HexEncoder();
                     byte[]     bytes      = hexEncoder.DecodeData(opReturnHexStr);
                     return(bytes);
                 }
             }
         }
     }
     return(null);
 }
Example #7
0
        public async Task KeyRepositoryTest()
        {
            using var tester = DBTrieRepositoryTester.Create(nameof(KeyRepositoryTest));

            Assert.Throws <FormatException>(() => tester.KeysRepository.InitializeFromSeed("bogus seed"));
            Assert.Throws <ArgumentOutOfRangeException>(() => tester.KeysRepository.InitializeFromSeed("deadbeef"));
            var seed = _keys[0].ToBytes();

            var pin = "my pin code";
            await tester.KeysRepository.EncryptSeedAndSaveToFile(seed, pin);

            // case 1: can decrypt seed with the same pin.
            var encryptedSeed = await tester.Config.TryGetEncryptedSeed();

            Assert.NotNull(encryptedSeed);
            var seed2 = tester.KeysRepository.DecryptEncryptedSeed(_hex.DecodeData(encryptedSeed), pin);

            Assert.Equal(Hex.Encode(seed), Hex.Encode(seed2));

            // case 2: can not with different pin
            var e = Assert.Throws <NRustLightningException>(() => tester.KeysRepository.DecryptEncryptedSeed(_hex.DecodeData(encryptedSeed), "bogus pin code"));

            Assert.Contains("Pin code mismatch", e.Message);
        }
Example #8
0
        private static void GetTransaction(AdmissionControl.AdmissionControl.AdmissionControlClient client, string accountHex, UInt64 seqNum)
        {
            Console.WriteLine($"GetTransaction for {accountHex} and seqnum {seqNum}.");

            HexEncoder hex = new HexEncoder();

            Types.UpdateToLatestLedgerRequest updToLatestLedgerReq = new Types.UpdateToLatestLedgerRequest();
            var getTxReq = new Types.GetAccountTransactionBySequenceNumberRequest();

            getTxReq.SequenceNumber = seqNum;
            getTxReq.Account        = Google.Protobuf.ByteString.CopyFrom(hex.DecodeData(accountHex));
            Types.RequestItem reqItem = new Types.RequestItem();
            reqItem.GetAccountTransactionBySequenceNumberRequest = getTxReq;
            updToLatestLedgerReq.RequestedItems.Add(reqItem);
            var reply = client.UpdateToLatestLedger(updToLatestLedgerReq);

            if (reply?.ResponseItems?.Count == 1)
            {
                var resp = reply.ResponseItems[0].GetAccountTransactionBySequenceNumberResponse;

                if (resp.SignedTransactionWithProof == null)
                {
                    Console.WriteLine("GetTransaction request did not return a signed transaction.");
                }
                else
                {
                    var    signedTx           = resp.SignedTransactionWithProof;
                    byte[] result             = signedTx.SignedTransaction.SignedTxn.ToByteArray();
                    var    deserializedResult = LCSCore.LCSDeserialization <RawTransactionLCS>(result);
                }
            }
            else
            {
                Console.WriteLine("GetTransaction did not return a result.");
            }
        }
Example #9
0
        public Config LoadArgs(IConfiguration config, ILogger logger)
        {
            var networkType = config.GetNetworkType();

            logger.LogInformation($"Network type: {networkType}");
            NetworkProvider = new NRustLightningNetworkProvider(networkType);
            var defaultSettings = NRustLightningDefaultSettings.GetDefaultSettings(NetworkProvider.NetworkType);

            DataDir = config.GetOrDefault <string>("datadir", null);
            if (DataDir is null)
            {
                DataDir = Path.GetDirectoryName(defaultSettings.DefaultDataDir);
                if (!Directory.Exists(DataDir))
                {
                    Directory.CreateDirectory(DataDir);
                }
                if (!Directory.Exists(defaultSettings.DefaultDataDir))
                {
                    Directory.CreateDirectory(defaultSettings.DefaultDataDir);
                }
            }

            var nbxConfig     = config.GetSection("nbx");
            var nbxCookieFile =
                nbxConfig.GetOrDefault("cookiefile",
                                       Constants.DefaultNBXplorerCookieFile(NetworkProvider.NetworkType));

            NBXplorerUri = new Uri(nbxConfig.GetOrDefault("rpcurl", Constants.DefaultNBXplorerUri));

            if (!File.Exists(nbxCookieFile))
            {
                logger.LogWarning($"cookie file for nbxplorer does not exist in {nbxCookieFile}" +
                                  " Make sure you are running nbx with --noauth.");
            }

            logger.LogInformation($"nbxplorer url {NBXplorerUri}");
            NBXCookieFile = nbxCookieFile;

            var p2pExternalIp = config.GetOrDefault("externalip", Constants.DefaultP2PExternalIpStr);

            if (IPEndPoint.TryParse(p2pExternalIp, out var ip))
            {
                P2PExternalIp = ip;
            }
            else if (p2pExternalIp.Contains(":"))
            {
                var s = p2pExternalIp.Split(":", StringSplitOptions.RemoveEmptyEntries);
                if (s.Length != 2)
                {
                    throw new ConfigException($"Invalid external ip {p2pExternalIp}");
                }

                if (Int32.TryParse(s[1], out var port))
                {
                    P2PExternalIp = new DnsEndPoint(s[0], port);
                }
                else
                {
                    throw new ConfigException($"Invalid external ip {p2pExternalIp}");
                }
            }
            else
            {
                throw new ConfigException($"Invalid external ip {p2pExternalIp}");
            }

            logger.LogInformation($"Advertising external ip: {P2PExternalIp.ToEndpointString()}");
            logger.LogDebug($"Network: {NetworkProvider.NetworkType.ToString()}");
            var supportedChains = config.GetOrDefault <string>("chains", "BTC")
                                  .Split(',', StringSplitOptions.RemoveEmptyEntries)
                                  .Select(t => t.ToLowerInvariant());
            var validChains = new List <string>();

            foreach (var n in NetworkProvider.GetAll())
            {
                if (supportedChains.Contains(n.CryptoCode))
                {
                    validChains.Add(n.CryptoCode);
                    var chainConfiguration = new ChainConfiguration();
                    chainConfiguration.CryptoCode = n.CryptoCode;
                    var args = RPCArgs.Parse(config, n.NBitcoinNetwork, n.CryptoCode);
                    chainConfiguration.Rpc = args.ConfigureRPCClient(n, logger);
                    if (chainConfiguration.Rpc.Address.Port == n.NBitcoinNetwork.DefaultPort)
                    {
                        logger.LogWarning($"{n.CryptoCode}: It seems that theļ¼‘ RPC port ({chainConfiguration.Rpc.Address.Port}) is equal to the default P2P port ({n.NBitcoinNetwork.DefaultPort}, this is probably a misconfiguration)");
                    }
                    if ((chainConfiguration.Rpc.CredentialString.CookieFile != null || chainConfiguration.Rpc.CredentialString.UseDefault) && !n.SupportCookieAuthentication)
                    {
                        throw new ConfigException($"Chain {n.CryptoCode} does not support cookie file authentication,\n" +
                                                  $"Please use {n.CryptoCode.ToLowerInvariant()}rpcuser and {n.CryptoCode.ToLowerInvariant()}rpcpassword settings in NRustLightning" +
                                                  $"And configure rpcuser and rpcpassword in the configuration file or in commandline or your node");
                    }
                    ChainConfiguration.Add(chainConfiguration);
                }
            }
            var invalidChains = String.Join(',', supportedChains.Where(s => !validChains.Contains(s)));

            if (!string.IsNullOrEmpty(invalidChains))
            {
                throw new ConfigException($"Invalid chains {invalidChains}");
            }

            config.GetSection("ln").Bind(RustLightningConfig);

            string?seed     = null;
            var    filePath = Path.Join(DataDir, "node_secret");

            if (File.Exists(filePath))
            {
                logger.LogDebug($"reading seed from {filePath}");
                seed = File.ReadAllText(filePath);
            }
            if (seed is null)
            {
                seed = config.GetOrDefault("seed", String.Empty);
            }
            if (String.IsNullOrEmpty(seed))
            {
                logger.LogWarning($"seed not found in {filePath}! You can specify it with --seed option.");
                logger.LogInformation("generating new seed...");
                seed = RandomUtils.GetUInt256().ToString();
            }

            InvoiceDBFilePath = Path.Combine(DataDir, "InvoiceDb");
            if (!Directory.Exists(InvoiceDBFilePath))
            {
                Directory.CreateDirectory(InvoiceDBFilePath);
            }

            var h = new HexEncoder();

            if (!(h.IsValid(seed) && seed.Length == 64))
            {
                throw new NRustLightningException($"Seed corrupted {seed}");
            }
            File.WriteAllText(filePath, seed);
            GetSeed = async() => {
                var s = await File.ReadAllTextAsync(filePath);

                return(h.DecodeData(s));
            };

            PaymentTimeoutSec = config.GetOrDefault("paymenttimeout", Constants.DefaultPaymentTimeoutSec);

            DBCacheMB = config.GetOrDefault("dbcache", Constants.DefaultDBCacheMB);
            return(this);
        }
Example #10
0
        public void TestExtract()
        {
            var extractVectors = (ReadJson("extract.json"));

            Assert.NotEmpty(extractVectors);
            foreach (var token in extractVectors)
            {
                var a            = ((JObject)token).GetValue("a").ToString();
                var extractedKey = new byte[ExtractedKeySize];
                var vecA         = _hex.DecodeData(a);
                var b            = ((JObject)token).GetValue("b").ToString();
                var vecB         = _hex.DecodeData(b);
                AEZ.Extract(vecA, extractedKey);
                Assert.Equal(_hex.EncodeData(vecB), _hex.EncodeData(extractedKey));
            }
        }
Example #11
0
        private static Command Connect()
        {
            var c   = new Command("connect", "connect to other lightning node");
            var op1 = new Option(new [] { "--nodeid", "--pubkey" }, "hex-encoded public key of the node we want to connect to")
            {
                Argument = new Argument <string>
                {
                    Arity = ArgumentArity.ExactlyOne
                }
            };

            op1.AddValidator(r =>
            {
                var msg = "Must specify valid pubkey in hex";
                var v   = r.GetValueOrDefault <string>();

                if (String.IsNullOrEmpty(v))
                {
                    return(msg);
                }

                if (!HexEncoder.IsWellFormed(v))
                {
                    return($"Invalid hex for pubkey: {v}");
                }

                var hexEncoder = new HexEncoder();
                var b          = hexEncoder.DecodeData(v);

                if (!PubKey.Check(b, true))
                {
                    return($"Invalid pubkey {v}");
                }
                return(null);
            });
            c.AddOption(op1);

            var op2 = new Option("--host", "ip:port pair of the node")
            {
                Argument = new Argument <string>
                {
                    Arity = ArgumentArity.ExactlyOne
                }
            };

            op2.AddValidator(r =>
            {
                var v = r.GetValueOrDefault <string>();

                if (String.IsNullOrEmpty(v))
                {
                    return("Invalid host");
                }

                if (!NBitcoin.Utils.TryParseEndpoint(v, 80, out var _))
                {
                    return("Invalid host");
                }

                return(null);
            });
            c.AddOption(op2);
            return(c);
        }
Example #12
0
 public override byte[] GetBytes(string s)
 {
     return(_encoder.DecodeData(s));
 }