示例#1
0
        public void CanCacheNoSqlRepository()
        {
            var cached = new CachedNoSqlRepository(new InMemoryNoSqlRepository());

            byte[] data1 = new byte[] { 1, 2, 3, 4, 5, 6 };
            byte[] data2 = new byte[] { 11, 22, 33, 4, 5, 66 };
            cached.InnerRepository.Put("data1", new RawData(data1));
            Assert.NotNull(cached.Get <RawData>("data1"));
            cached.InnerRepository.Put("data1", new RawData(data2));
            cached.Flush();
            var data1Actual = cached.InnerRepository.Get <RawData>("data1");

            AssertEx.CollectionEquals(data1Actual.Data, data2);
            cached.Put("data1", new RawData(data1));

            data1Actual = cached.InnerRepository.Get <RawData>("data1");
            AssertEx.CollectionEquals(data1Actual.Data, data2);

            cached.Flush();

            data1Actual = cached.InnerRepository.Get <RawData>("data1");
            AssertEx.CollectionEquals(data1Actual.Data, data1);

            cached.Put("data1", null);
            cached.Flush();
            Assert.Null(cached.InnerRepository.Get <RawData>("data1"));

            cached.Put("data1", new RawData(data1));
            cached.Put("data1", null);
            cached.Flush();
            Assert.Null(cached.InnerRepository.Get <RawData>("data1"));

            cached.Put("data1", null);
            cached.Put("data1", new RawData(data1));
            cached.Flush();
            Assert.NotNull(cached.InnerRepository.Get <RawData>("data1"));
        }
示例#2
0
        public void EncryptedSecretECmultiplyNoLotSimple()
        {
            var compressedValues = new[] { false, true };

            foreach (var compressed in compressedValues)
            {
                var code = new BitcoinPassphraseCode("test", Network.Main, null);
                Assert.Null(code.LotSequence);
                var result = code.GenerateEncryptedSecret(compressed);
                Assert.True(result.ConfirmationCode.Check("test", result.GeneratedAddress));
                Assert.False(result.ConfirmationCode.Check("toto", result.GeneratedAddress));
                Assert.False(result.ConfirmationCode.Check("test", new Key().PubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main)));

                var decryptedKey = result.EncryptedKey.GetKey("test");
                Assert.Equal(result.GeneratedAddress.ToString(), decryptedKey.PubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main).ToString());

                Assert.Throws <SecurityException>(() => result.EncryptedKey.GetKey("wrong"));

                //Can regenerate same result with same seed
                var result2       = code.GenerateEncryptedSecret(compressed, seedb: result.Seed);
                var decryptedKey2 = result.EncryptedKey.GetKey("test");
                AssertEx.CollectionEquals(decryptedKey2.ToBytes(), decryptedKey.ToBytes());
            }
        }
        public void CanCreatePayment()
        {
            var tests = new[]
            {
                new CanCreatePaymentData
                {
                    //sx stealth-newkey
                    StealthAddress = "vJmtjxSDxNPXL4RNapp9ARdqKz3uJyf1EDGjr1Fgqs9c8mYsVH82h8wvnA4i5rtJ57mr3kor1EVJrd4e5upACJd588xe52yXtzumxj",

                    ScanSecret = "3e49e7257cb31db997edb1cf8299af0f37e2663e2260e4b8033e49d39a6d02f2",
                    ScanPubKey = "025e58a31122b38c86abc119b9379fe247410aee87a533f9c07b189aef6c3c1f52",

                    SpendSecret = "aa3db0cfb3edc94de4d10f873f8190843f2a17484f6021a95a7742302c744748",
                    SpendPubKey = "03616562c98e7d7b74be409a787cec3a912122f3fb331a9bee9b0b73ce7b9f50af",

                    //sx newkey | sx wif-to-secret
                    EphemSecret = "9e63abaf8dcd5ea3919e6de0b6c544e00bf51bf92496113a01d6e369944dc091",
                    EphemPubKey = "03403d306ec35238384c7e340393335f9bc9bb4a2e574eb4e419452c4ea19f14b0",

                    //sx steatlh-uncover-secret [EphemPubKey] [ScanSecret] [SpendSecret]
                    StealthSecret = "4e422fb1e5e1db6c1f6ab32a7706d368ceb385e7fab098e633c5c5949c3b97cd",
                    //sx stealth-initiate [EphemSecret] [ScanPubKey] [SpendPubKey] (for sender)
                    //or
                    //sx stealth-uncover [EphemPubKey] [ScanSecret] [SpendPubKey]  (for receiver)
                    StealthPubKey = "02726112ad39cb6bf848b1b1ef30b88e35286bf99f746c2be575f96c0e02a9357c",
                },

                //Need padding for to find the stealth secret
                new CanCreatePaymentData {
                    StealthAddress = "vJmyTEybwCKz7W8y6vP62jo7RoyfLneiANcPLBBNYwn98EXzQRStMKqKGRiZhqscuQ6WKy2J3U3zfx72V3b2J6YvxxBcxUj4XMDsw7",
                    ScanSecret     = "2f517d81cf30e47dbf4809321275bbfd92192af81a6141a17aa53e40bd28fe36",
                    ScanPubKey     = "039d91ae0eebea6dc500fb57b704abce3d3fa700cc762a52bc5dcaee27770a8402",
                    SpendSecret    = "71e33219884fc27011f8da9adcc730f0c2e940759bdb1b615764492bce04fcea",
                    SpendPubKey    = "021a3d5b40ec83fc58b5a23207eb9c99b741d8f0e9f8b80f04f49cec915b540c40",
                    EphemSecret    = "578ffe42c0fbfb324a31f41dbbcd8b1f910ce2f4d803444a83b18ae9f8ccd97e",
                    EphemPubKey    = "03c190be0a1c6e50577b3dd637b1fff9344de31c2544ff3d815535c0515711150f",
                    StealthSecret  = "006d138b4bcef0f09c8784c0cc68f2be4497a1a822d8d7b0519c5c0378b5cb45",
                    StealthPubKey  = "0223a99278a5279ea93718503a42377067e72960eb808d8bff6defdd95d4feff76"
                }
            };

            foreach (var test in tests)
            {
                var scan    = AssertKeys(test.ScanSecret, test.ScanPubKey);
                var spend   = AssertKeys(test.SpendSecret, test.SpendPubKey);
                var ephem   = AssertKeys(test.EphemSecret, test.EphemPubKey);
                var stealth = AssertKeys(test.StealthSecret, test.StealthPubKey);

                var address = spend.PubKey.CreateStealthAddress(scan.PubKey, Network.Main);
                Assert.Equal(test.StealthAddress, address.ToString());
                //Try roundtrip
                address = new BitcoinStealthAddress(address.ToBytes(), Network.Main);
                Assert.Equal(test.StealthAddress, address.ToString());

                var payment      = address.CreatePayment(ephem);
                var generatedKey = spend.Uncover(scan, payment.Metadata.EphemKey);
                if (stealth != null)
                {
                    Assert.Equal(stealth.PubKey.Hash, payment.StealthKeys[0].ID);
                    Assert.Equal(stealth.ToBytes(), generatedKey.ToBytes());
                }
                var uncoveredSender    = spend.PubKey.UncoverSender(ephem, scan.PubKey);
                var uncovertedReceiver = spend.PubKey.UncoverReceiver(scan, ephem.PubKey);

                AssertEx.CollectionEquals(uncoveredSender.ToBytes(), uncovertedReceiver.ToBytes());
                AssertEx.CollectionEquals(generatedKey.PubKey.ToBytes(), uncovertedReceiver.ToBytes());

                var transaction = Network.Main.CreateTransaction();
                payment.AddToTransaction(transaction, 100UL);
            }
        }
示例#4
0
		public void ShouldPassTheLongestTestInBIP174()
		{
			JObject testcase = (JObject)testdata["final"];
			var network = Network.TestNet;
			var master = ExtKey.Parse((string)testcase["master"], network);
			var masterFP = master.PrivateKey.PubKey.GetHDFingerPrint();
			var tx = network.CreateTransaction();
			tx.Version = 2;

			var scriptPubKey1 = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)testcase["out1"]["script"]));
			var money1 = Money.Coins((decimal)testcase["out1"]["value"]);
			var scriptPubKey2 = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)testcase["out2"]["script"]));
			var money2 = Money.Coins((decimal)testcase["out2"]["value"]);
			tx.Outputs.Add(new TxOut(value: money1, scriptPubKey: scriptPubKey1));
			tx.Outputs.Add(new TxOut(value: money2, scriptPubKey: scriptPubKey2));
			tx.Inputs.Add(new OutPoint(uint256.Parse((string)testcase["in1"]["txid"]), (uint)testcase["in1"]["index"]));
			tx.Inputs.Add(new OutPoint(uint256.Parse((string)testcase["in2"]["txid"]), (uint)testcase["in2"]["index"]));

			var expected = PSBT.Parse((string)testcase["psbt1"], Network.Main);

			var psbt = PSBT.FromTransaction(tx, Network.Main);
			Assert.Equal(expected, psbt, ComparerInstance);

			var prevtx1 = Transaction.Parse((string)testcase["prevtx1"], network);
			var prevtx2 = Transaction.Parse((string)testcase["prevtx2"], network);
			psbt.AddTransactions(prevtx1, prevtx2);
			var redeem1 = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)testcase["redeem1"]));
			var redeem2 = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)testcase["redeem2"]));
			var witness_script1 = Script.FromBytesUnsafe(Encoders.Hex.DecodeData((string)testcase["witness1"]));
			psbt.AddScripts(new[] { redeem1, redeem2, witness_script1 });

			for (int i = 0; i < 6; i++)
			{
				var pk = testcase[$"pubkey{i}"];
				var pubkey = new PubKey((string)pk["hex"]);
				var path = KeyPath.Parse((string)pk["path"]);
				psbt.AddKeyPath(pubkey, new RootedKeyPath(masterFP, path));
			}

			expected = PSBT.Parse((string)testcase["psbt2"], Network.Main);
			Assert.Equal(expected, psbt, ComparerInstance);

			foreach(var psbtin in psbt.Inputs)
				psbtin.SighashType = SigHash.All;
			expected = PSBT.Parse((string)testcase["psbt3"], Network.Main);
			Assert.Equal(expected, psbt, ComparerInstance);

			psbt.AssertSanity();
			var psbtForBob = psbt.Clone();

			// path 1 ... alice
			Assert.Equal(psbt, psbtForBob, ComparerInstance);
			var aliceKey1 = master.Derive(new KeyPath((string)testcase["key7"]["path"])).PrivateKey;
			var aliceKey2 = master.Derive(new KeyPath((string)testcase["key8"]["path"])).PrivateKey;
			psbt.SignWithKeys(aliceKey1, aliceKey2);
			expected = PSBT.Parse((string)testcase["psbt4"], Network.Main);
			Assert.Equal(expected, psbt);

			// path 2 ... bob.
			var bobKey1 = master.Derive(new KeyPath((string)testcase["key9"]["path"])).PrivateKey;
			var bobKey2 = master.Derive(new KeyPath((string)testcase["key10"]["path"])).PrivateKey;
			var bobKeyhex1 = (string)testcase["key9"]["wif"];
			var bobKeyhex2 = (string)testcase["key10"]["wif"];
			Assert.Equal(bobKey1, new BitcoinSecret(bobKeyhex1, network).PrivateKey);
			Assert.Equal(bobKey2, new BitcoinSecret(bobKeyhex2, network).PrivateKey);
			psbtForBob.Settings.UseLowR = false;
			psbtForBob.SignWithKeys(bobKey1, bobKey2);
			expected = PSBT.Parse((string)testcase["psbt5"], Network.Main);
			Assert.Equal(expected, psbtForBob);

			// merge above 2
			var combined = psbt.Combine(psbtForBob);
			expected = PSBT.Parse((string)testcase["psbtcombined"], Network.Main);
			Assert.Equal(expected, combined);

			Assert.True(combined.TryGetFee(out var fee));
			Assert.Equal(Money.Coins(0.00010000m), fee);
			Assert.True(combined.TryGetEstimatedFeeRate(out var feeRate));
			Assert.Equal(new FeeRate(21.6m).SatoshiPerByte, feeRate.SatoshiPerByte, 1);

			var finalized = psbt.Finalize();
			expected = PSBT.Parse((string)testcase["psbtfinalized"], Network.Main);
			Assert.Equal(expected, finalized);

			var finalTX = psbt.ExtractTransaction();
			var expectedTX = Transaction.Parse((string)testcase["txextracted"], network);
			AssertEx.CollectionEquals(expectedTX.ToBytes(), finalTX.ToBytes());

			Assert.True(psbt.TryGetFee(out fee));
			Assert.Equal(Money.Coins(0.00010000m), fee);
			Assert.True(psbt.TryGetEstimatedFeeRate(out feeRate));
			Assert.Equal(new FeeRate(21.6m).SatoshiPerByte, feeRate.SatoshiPerByte, 2);
		}
        public void CanConvertText()
        {
            string testPhrase = "é ^ç hello \"12345\"  wooorld";
            var    tests      = new[]
            {
                new
                {
                    Encoder  = Encoders.Hex,
                    Input    = testPhrase,
                    Expected = "c3a9205ec3a72068656c6c6f20223132333435222020776f6f6f726c64",
                },
                new
                {
                    Encoder  = Encoders.Base58,
                    Input    = testPhrase,
                    Expected = "9tBRc991GhmZNsV5qSyynUsnRCNvxdvvWDmj3nAP"
                },
                new
                {
                    Encoder = Encoders.Base58Check,
                    Input   = testPhrase,
                    //Different from brainwallet, because brainwallet code convert the data to bitcoin address instead of directely formating in base58check (ie : the data followed be the 4 hash bytes)
                    Expected = "2189xoVGsHC6VbVPUrKeH3fhT429VDruzdgUJFk37PNskG"
                },
                new
                {
                    Encoder  = Encoders.Base64,
                    Input    = testPhrase,
                    Expected = "w6kgXsOnIGhlbGxvICIxMjM0NSIgIHdvb29ybGQ="
                },
                //Not yet implemented
                //new
                //{
                //	Encoder = Encoders.Bin,
                //	Input = testPhrase,
                //	Expected = "11000011 10101001 00100000 01011110 11000011 10100111 00100000 01101000 01100101 01101100 01101100 01101111 00100000 00100010 00110001 00110010 00110011 00110100 00110101 00100010 00100000 00100000 01110111 01101111 01101111 01101111 01110010 01101100 01100100"
                //},
                //Not yet implemented
                //new
                //{
                //	Encoder = Encoders.Dec,
                //	Input = testPhrase,
                //	Expected = "5275000693703128425041367611933003709099386868005962673424426230508644"
                //},
                //Useless for bitcoin
                //new
                //{
                //	Encoder = Encoders.RFC1751,
                //	Input = testPhrase,
                //	Expected = "A A OWE BANG BAN BUST KITE ARK HAT SEEN OBOE GRIM KIN GASH GLOB COAT BANE DUN JO MILL SIGH SLID MAD PAR"
                //},
                //Useless for bitcoin
                //new
                //{
                //	Encoder = Encoders.Poetry,
                //	Input = testPhrase,
                //	Expected = "perfect perfect perfect soul stone royal fault companion sharp cross build leap possess possibly yet bone magic beam illuminate moonlight foul juice darkness universe"
                //},
                //Useless for bitcoin
                //new
                //{
                //	Encoder = Encoders.Rot13,
                //	Input = testPhrase,
                //	Expected = "é ^ç uryyb \"12345\"  jbbbeyq"
                //},
                //Useless for bitcoin
                //new
                //{
                //	Encoder = Encoders.Easy16,
                //	Input = testPhrase,
                //	Expected = "aaaa aauf reda houf rkda jwjh juju jnda eriu\r\nddfs fdff fgfh ddda dakk jnjn jnkd jujg euhs"
                //},
            };

            foreach (var test in tests)
            {
                var input   = Encoding.UTF8.GetBytes(test.Input);
                var encoded = test.Encoder.EncodeData(input);
                Assert.Equal(test.Expected, encoded);

                try
                {
                    var decoded = test.Encoder.DecodeData(encoded);
                    AssertEx.CollectionEquals(input, decoded);
                }
                catch (NotSupportedException)
                {
                }
            }

            var expectedText = "2189xoVGsHC6VbVPUrKeH3fhT429VDruzdgUJFk37PNskG";
            var input1       = Encoding.UTF8.GetBytes("---é ^ç hello \"12345\"  wooorld---");
            var encoded1     = Encoders.Base58Check.EncodeData(input1, 3, input1.Length - 6);

            Assert.Equal(expectedText, encoded1);

            var decoded1 = Encoders.Base58Check.DecodeData(encoded1);

            byte[] arr = new byte[input1.Length - 6];
            Array.Copy(input1, 3, arr, 0, arr.Length);
            AssertEx.CollectionEquals(input1.SafeSubarray(3, input1.Length - 6), decoded1);
        }