Esempio n. 1
0
 /// <summary>
 /// Used only in creation of the genesis blocks and in unit tests.
 /// </summary>
 internal TransactionOutput(NetworkParameters @params, byte[] scriptBytes)
     : base(@params)
 {
     _scriptBytes = scriptBytes;
     _value = Utils.ToNanoCoins(50, 0);
     _availableForSpending = true;
 }
Esempio n. 2
0
 /// <summary>
 /// Parses the given private key as created by the "dumpprivkey" BitCoin C++ RPC.
 /// </summary>
 /// <param name="params">The expected network parameters of the key. If you don't care, provide null.</param>
 /// <param name="encoded">The base58 encoded string.</param>
 /// <exception cref="BitCoinSharp.AddressFormatException">If the string is invalid or the header byte doesn't match the network params.</exception>
 public DumpedPrivateKey(NetworkParameters @params, string encoded)
     : base(encoded)
 {
     if (@params != null && Version != @params.DumpedPrivateKeyHeader)
         throw new AddressFormatException("Mismatched version number, trying to cross networks? " + Version +
                                          " vs " + @params.DumpedPrivateKeyHeader);
 }
Esempio n. 3
0
 /// <summary>
 /// Construct an address from parameters and the standard "human readable" form.
 /// </summary>
 /// <remarks>
 /// Example:<p/>
 /// <pre>new Address(NetworkParameters.prodNet(), "17kzeh4N8g49GFvdDzSf8PjaPfyoD1MndL");</pre>
 /// </remarks>
 /// <exception cref="AddressFormatException"/>
 public Address(NetworkParameters @params, string address)
     : base(address)
 {
     if (Version != @params.AddressHeader)
         throw new AddressFormatException("Mismatched version number, trying to cross networks? " + Version +
                                          " vs " + @params.AddressHeader);
 }
Esempio n. 4
0
 internal Transaction(NetworkParameters @params)
     : base(@params)
 {
     _version = 1;
     _inputs = new List<TransactionInput>();
     _outputs = new List<TransactionOutput>();
     // We don't initialize appearsIn deliberately as it's only useful for transactions stored in the wallet.
 }
Esempio n. 5
0
 internal TransactionOutput(NetworkParameters @params, Transaction parent, ulong value, Address to)
     : base(@params)
 {
     _value = value;
     _scriptBytes = Script.CreateOutputScript(to);
     ParentTransaction = parent;
     _availableForSpending = true;
 }
Esempio n. 6
0
 /// <summary>
 /// Used only in creation of the genesis block.
 /// </summary>
 internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] scriptBytes)
     : base(@params)
 {
     ScriptBytes = scriptBytes;
     Outpoint = new TransactionOutPoint(@params, -1, null);
     _sequence = uint.MaxValue;
     ParentTransaction = parentTransaction;
 }
Esempio n. 7
0
        /// <summary>
        /// Connect to the given IP address using the port specified as part of the network parameters. Once construction
        /// is complete a functioning network channel is set up and running.
        /// </summary>
        /// <param name="peerAddress">IP address to connect to. IPv6 is not currently supported by BitCoin. If port is not positive the default port from params is used.</param>
        /// <param name="params">Defines which network to connect to and details of the protocol.</param>
        /// <param name="bestHeight">How many blocks are in our best chain</param>
        /// <param name="connectTimeout">Timeout in milliseconds when initially connecting to peer</param>
        /// <exception cref="IOException">If there is a network related failure.</exception>
        /// <exception cref="ProtocolException">If the version negotiation failed.</exception>
        public NetworkConnection(PeerAddress peerAddress, NetworkParameters @params, uint bestHeight, int connectTimeout)
        {
            _params = @params;
            _remoteIp = peerAddress.Addr;

            var port = (peerAddress.Port > 0) ? peerAddress.Port : @params.Port;

            var address = new IPEndPoint(_remoteIp, port);
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(address);
            _socket.SendTimeout = _socket.ReceiveTimeout = connectTimeout;

            _out = new NetworkStream(_socket, FileAccess.Write);
            _in = new NetworkStream(_socket, FileAccess.Read);

            // the version message never uses check-summing. Update check-summing property after version is read.
            _serializer = new BitcoinSerializer(@params, false);

            // Announce ourselves. This has to come first to connect to clients beyond v0.30.20.2 which wait to hear
            // from us until they send their version message back.
            WriteMessage(new VersionMessage(@params, bestHeight));
            // When connecting, the remote peer sends us a version message with various bits of
            // useful data in it. We need to know the peer protocol version before we can talk to it.
            _versionMessage = (VersionMessage) ReadMessage();
            // Now it's our turn ...
            // Send an ACK message stating we accept the peers protocol version.
            WriteMessage(new VersionAck());
            // And get one back ...
            ReadMessage();
            // Switch to the new protocol version.
            var peerVersion = _versionMessage.ClientVersion;
            _log.InfoFormat("Connected to peer: version={0}, subVer='{1}', services=0x{2:X}, time={3}, blocks={4}",
                            peerVersion,
                            _versionMessage.SubVer,
                            _versionMessage.LocalServices,
                            UnixTime.FromUnixTime(_versionMessage.Time),
                            _versionMessage.BestHeight
                );
            // BitCoinSharp is a client mode implementation. That means there's not much point in us talking to other client
            // mode nodes because we can't download the data from them we need to find/verify transactions.
            if (!_versionMessage.HasBlockChain())
            {
                // Shut down the socket
                try
                {
                    Shutdown();
                }
                catch (IOException)
                {
                    // ignore exceptions while aborting
                }
                throw new ProtocolException("Peer does not have a copy of the block chain.");
            }
            // newer clients use check-summing
            _serializer.UseChecksumming(peerVersion >= 209);
            // Handshake is done!
        }
Esempio n. 8
0
 /// <summary>
 /// Creates an UNSIGNED input that links to the given output
 /// </summary>
 internal TransactionInput(NetworkParameters @params, Transaction parentTransaction, TransactionOutput output)
     : base(@params)
 {
     var outputIndex = output.Index;
     Outpoint = new TransactionOutPoint(@params, outputIndex, output.ParentTransaction);
     ScriptBytes = EmptyArray;
     _sequence = uint.MaxValue;
     ParentTransaction = parentTransaction;
 }
Esempio n. 9
0
 public MemoryBlockStore(NetworkParameters @params)
 {
     _blockMap = new Dictionary<ByteBuffer, byte[]>();
     // Insert the genesis block.
     var genesisHeader = @params.GenesisBlock.CloneAsHeader();
     var storedGenesis = new StoredBlock(genesisHeader, genesisHeader.GetWork(), 0);
     Put(storedGenesis);
     SetChainHead(storedGenesis);
 }
Esempio n. 10
0
 /// <summary>
 /// Creates a new, empty wallet with no keys and no transactions. If you want to restore a wallet from disk instead,
 /// see loadFromFile.
 /// </summary>
 public Wallet(NetworkParameters @params)
 {
     _params = @params;
     Keychain = new List<EcKey>();
     Unspent = new Dictionary<Sha256Hash, Transaction>();
     Spent = new Dictionary<Sha256Hash, Transaction>();
     _inactive = new Dictionary<Sha256Hash, Transaction>();
     Pending = new Dictionary<Sha256Hash, Transaction>();
     _dead = new Dictionary<Sha256Hash, Transaction>();
 }
Esempio n. 11
0
 public VersionMessage(NetworkParameters @params, uint newBestHeight)
     : base(@params)
 {
     ClientVersion = NetworkParameters.ProtocolVersion;
     LocalServices = 0;
     Time = UnixTime.ToUnixTime(DateTime.UtcNow);
     // Note that the official client doesn't do anything with these, and finding out your own external IP address
     // is kind of tricky anyway, so we just put nonsense here for now.
     MyAddr = new PeerAddress(IPAddress.Loopback, @params.Port, 0);
     TheirAddr = new PeerAddress(IPAddress.Loopback, @params.Port, 0);
     SubVer = "BitCoinSharp 0.1";
     BestHeight = newBestHeight;
 }
 /// <exception cref="BitCoinSharp.BlockStoreException" />
 public BoundedOverheadBlockStore(NetworkParameters @params, FileInfo file)
 {
     _params = @params;
     _notFoundMarker = new StoredBlock(null, null, uint.MaxValue);
     try
     {
         Load(file);
     }
     catch (IOException e)
     {
         _log.Error("failed to load block store from file", e);
         CreateNewStore(@params, file);
     }
 }
Esempio n. 13
0
 internal TransactionOutPoint(NetworkParameters @params, int index, Transaction fromTx)
     : base(@params)
 {
     Index = index;
     if (fromTx != null)
     {
         Hash = fromTx.Hash;
         FromTx = fromTx;
     }
     else
     {
         // This happens when constructing the genesis block.
         Hash = Sha256Hash.ZeroHash;
     }
 }
Esempio n. 14
0
 /// <exception cref="BitCoinSharp.BlockStoreException" />
 public DiskBlockStore(NetworkParameters @params, FileInfo file)
 {
     _params = @params;
     _blockMap = new Dictionary<Sha256Hash, StoredBlock>();
     try
     {
         Load(file);
         if (_stream != null)
         {
             _stream.Dispose();
         }
         _stream = file.Open(FileMode.Append, FileAccess.Write); // Do append.
     }
     catch (IOException e)
     {
         _log.Error("failed to load block store from file", e);
         CreateNewStore(@params, file);
     }
 }
Esempio n. 15
0
 /// <exception cref="ProtocolException"/>
 internal Message(NetworkParameters @params, byte[] msg, int offset, uint protocolVersion = NetworkParameters.ProtocolVersion)
 {
     ProtocolVersion = protocolVersion;
     Params = @params;
     Bytes = msg;
     Cursor = Offset = offset;
     Parse();
     #if SELF_CHECK
     // Useful to ensure serialize/deserialize are consistent with each other.
     if (GetType() != typeof (VersionMessage))
     {
         var msgbytes = new byte[Cursor - offset];
         Array.Copy(msg, offset, msgbytes, 0, Cursor - offset);
         var reserialized = BitcoinSerialize();
         if (!reserialized.SequenceEqual(msgbytes))
             throw new Exception("Serialization is wrong: " + Environment.NewLine +
                                 Utils.BytesToHexString(reserialized) + " vs " + Environment.NewLine +
                                 Utils.BytesToHexString(msgbytes));
     }
     #endif
     Bytes = null;
 }
Esempio n. 16
0
 /// <exception cref="BitCoinSharp.ProtocolException" />
 public VersionMessage(NetworkParameters @params, byte[] msg)
     : base(@params, msg, 0)
 {
 }
Esempio n. 17
0
 public GetDataMessage(NetworkParameters @params)
     : base(@params)
 {
 }
Esempio n. 18
0
 public SeedPeers(NetworkParameters @params)
 {
     _params = @params;
 }
Esempio n. 19
0
 /// <summary>
 /// Allows the output of a private key in versioned, checksummed form.
 /// </summary>
 /// <param name="params">The network parameters of this key, needed for the version byte. </param>
 /// <param name="keyBytes">The 256-bit private key.</param>
 public DumpedPrivateKey(NetworkParameters @params, byte[] keyBytes)
     : base(@params.DumpedPrivateKeyHeader, keyBytes)
 {
     if (keyBytes.Length != 32) // 256 bit keys
         throw new ArgumentException("Keys are 256 bits, so you must provide 32 bytes.", "keyBytes");
 }
Esempio n. 20
0
 /// <summary>
 /// Sets up the given NetworkParameters with testnet values.
 /// </summary>
 private static NetworkParameters CreateTestNet(NetworkParameters n)
 {
     // Genesis hash is 0000000224b1593e3ff16a0e3b61285bbc393a39f78c8aa48c456142671f7110
     // The proof of work limit has to start with 00, as otherwise the value will be interpreted as negative.
     n.ProofOfWorkLimit = new BigInteger("0000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
     n.PacketMagic = 0xfabfb5da;
     n.Port = 18333;
     n.AddressHeader = 111;
     n.DumpedPrivateKeyHeader = 239;
     n.Interval = _interval;
     n.TargetTimespan = _targetTimespan;
     n.GenesisBlock = CreateGenesis(n);
     n.GenesisBlock.Time = 1296688602;
     n.GenesisBlock.DifficultyTarget = 0x1d07fff8;
     n.GenesisBlock.Nonce = 384568319;
     var genesisHash = n.GenesisBlock.HashAsString;
     Debug.Assert(genesisHash.Equals("00000007199508e34a9ff81e6ec0c477a4cccff2a4767a8eee39c11db367b008"));
     return n;
 }
Esempio n. 21
0
 /// <exception cref="ProtocolException"/>
 internal AddressMessage(NetworkParameters networkParams, byte[] payload)
     : base(networkParams, payload, 0)
 {
 }
Esempio n. 22
0
 internal Message(NetworkParameters @params)
 {
     Params = @params;
 }
Esempio n. 23
0
 /// <summary>
 /// Exports the private key in the form used by the Satoshi client "dumpprivkey" and "importprivkey" commands. Use
 /// the <see cref="DumpedPrivateKey.ToString"/> method to get the string.
 /// </summary>
 /// <param name="params">The network this key is intended for use on.</param>
 /// <returns>Private key bytes as a <see cref="DumpedPrivateKey"/>.</returns>
 public DumpedPrivateKey GetPrivateKeyEncoded(NetworkParameters @params)
 {
     return(new DumpedPrivateKey(@params, GetPrivKeyBytes()));
 }
Esempio n. 24
0
 internal Message(NetworkParameters @params)
 {
     Params = @params;
 }
Esempio n. 25
0
 /// <exception cref="ProtocolException"/>
 public VersionMessage(NetworkParameters networkParams, byte[] msg)
     : base(networkParams, msg, 0)
 {
 }
 /// <summary>
 /// Constructs a BitcoinSerializer with the given behavior.
 /// </summary>
 /// <param name="params">MetworkParams used to create Messages instances and determining packetMagic</param>
 /// <param name="usesChecksumming">Set to true if checksums should be included and expected in headers</param>
 public BitcoinSerializer(NetworkParameters @params, bool usesChecksumming)
 {
     _params           = @params;
     _usesChecksumming = usesChecksumming;
 }
Esempio n. 27
0
 /// <summary>
 /// Deserializes an input message. This is usually part of a transaction message.
 /// </summary>
 /// <exception cref="BitCoinSharp.ProtocolException" />
 public TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] payload, int offset)
     : base(@params, payload, offset)
 {
     ParentTransaction = parentTransaction;
 }
Esempio n. 28
0
        /// <summary>
        /// The test chain created by Gavin.
        /// </summary>
        public static NetworkParameters TestNet()
        {
            var n = new NetworkParameters();

            return(CreateTestNet(n));
        }
Esempio n. 29
0
 public ListMessage(NetworkParameters @params)
     : base(@params)
 {
     _items = new List<InventoryItem>();
 }
Esempio n. 30
0
 /// <summary>
 /// The primary BitCoin chain created by Satoshi.
 /// </summary>
 public static NetworkParameters ProdNet()
 {
     var n = new NetworkParameters();
     n.ProofOfWorkLimit = new BigInteger("00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
     n.Port = 8333;
     n.PacketMagic = 0xf9beb4d9;
     n.AddressHeader = 0;
     n.DumpedPrivateKeyHeader = 128;
     n.Interval = _interval;
     n.TargetTimespan = _targetTimespan;
     n.GenesisBlock = CreateGenesis(n);
     n.GenesisBlock.DifficultyTarget = 0x1d00ffff;
     n.GenesisBlock.Time = 1231006505;
     n.GenesisBlock.Nonce = 2083236893;
     var genesisHash = n.GenesisBlock.HashAsString;
     Debug.Assert(genesisHash.Equals("000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f"), genesisHash);
     return n;
 }
Esempio n. 31
0
 /// <summary>
 /// Returns a testnet params modified to allow any difficulty target.
 /// </summary>
 internal static NetworkParameters UnitTests()
 {
     var n = new NetworkParameters();
     n = CreateTestNet(n);
     n.ProofOfWorkLimit = new BigInteger("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 16);
     n.GenesisBlock.DifficultyTarget = Block.EasiestDifficultyTarget;
     n.Interval = 10;
     n.TargetTimespan = 200000000; // 6 years. Just a very big number.
     return n;
 }
Esempio n. 32
0
 /// <exception cref="ProtocolException"/>
 internal AddressMessage(NetworkParameters networkParams, byte[] payload, int offset)
     : base(networkParams, payload, offset)
 {
 }
Esempio n. 33
0
 /// <summary>
 /// The test chain created by Gavin.
 /// </summary>
 public static NetworkParameters TestNet()
 {
     var n = new NetworkParameters();
     return CreateTestNet(n);
 }
Esempio n. 34
0
 /// <summary>
 /// Construct a Script using the given network parameters and a range of the programBytes array.
 /// </summary>
 /// <param name="params">Network parameters.</param>
 /// <param name="programBytes">Array of program bytes from a transaction.</param>
 /// <param name="offset">How many bytes into programBytes to start reading from.</param>
 /// <param name="length">How many bytes to read.</param>
 /// <exception cref="ScriptException"/>
 public Script(NetworkParameters @params, byte[] programBytes, int offset, int length)
 {
     _params = @params;
     Parse(programBytes, offset, length);
 }
Esempio n. 35
0
 private static Block CreateGenesis(NetworkParameters n)
 {
     var genesisBlock = new Block(n);
     var t = new Transaction(n);
     try
     {
         // A script containing the difficulty bits and the following message:
         //
         //   "The Times 03/Jan/2009 Chancellor on brink of second bailout for banks"
         var bytes = Hex.Decode("04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73");
         t.AddInput(new TransactionInput(n, t, bytes));
         using (var scriptPubKeyBytes = new MemoryStream())
         {
             Script.WriteBytes(scriptPubKeyBytes, Hex.Decode("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f"));
             scriptPubKeyBytes.Write(Script.OpCheckSig);
             t.AddOutput(new TransactionOutput(n, scriptPubKeyBytes.ToArray()));
         }
     }
     catch (Exception)
     {
     }
     genesisBlock.AddTransaction(t);
     return genesisBlock;
 }
Esempio n. 36
0
        /// <summary>
        /// Returns the address that corresponds to the public part of this ECKey. Note that an address is derived from
        /// the RIPEMD-160 hash of the public key and is not the public key itself (which is too large to be convenient).
        /// </summary>
        public Address ToAddress(NetworkParameters @params)
        {
            var hash160 = Utils.Sha256Hash160(_pub);

            return(new Address(@params, hash160));
        }
Esempio n. 37
0
        private byte[] _programCopy; // TODO: remove this

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Construct a Script using the given network parameters and a range of the programBytes array.
        /// </summary>
        /// <param name="params">Network parameters.</param>
        /// <param name="programBytes">Array of program bytes from a transaction.</param>
        /// <param name="offset">How many bytes into programBytes to start reading from.</param>
        /// <param name="length">How many bytes to read.</param>
        /// <exception cref="ScriptException"/>
        public Script(NetworkParameters @params, byte[] programBytes, int offset, int length)
        {
            _params = @params;
            Parse(programBytes, offset, length);
        }
Esempio n. 38
0
 /// <summary>
 /// Construct a peer address from a serialized payload.
 /// </summary>
 /// <exception cref="ProtocolException"/>
 public PeerAddress(NetworkParameters networkParams, byte[] payload, int offset, uint protocolVersion)
     : base(networkParams, payload, offset, protocolVersion)
 {
 }
Esempio n. 39
0
 internal Message(NetworkParameters networkParams)
 {
     Params = networkParams;
 }
Esempio n. 40
0
 /// <summary>
 /// Constructs a BlockChain connected to the given list of wallets and a store.
 /// </summary>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, IEnumerable<Wallet> wallets, IBlockStore blockStore)
 {
     _blockStore = blockStore;
     _chainHead = blockStore.GetChainHead();
     _log.InfoFormat("chain head is:{0}{1}", Environment.NewLine, _chainHead.Header);
     _params = @params;
     _wallets = new List<Wallet>(wallets);
 }
Esempio n. 41
0
 /// <summary>
 /// Deserializes an input message. This is usually part of a transaction message.
 /// </summary>
 /// <exception cref="BitCoinSharp.ProtocolException" />
 public TransactionInput(NetworkParameters @params, Transaction parentTransaction, byte[] payload, int offset)
     : base(@params, payload, offset)
 {
     ParentTransaction = parentTransaction;
 }
Esempio n. 42
0
 /// <summary>
 /// Constructs a BlockChain connected to the given wallet and store. To obtain a <see cref="Wallet"/> you can construct
 /// one from scratch, or you can deserialize a saved wallet from disk using <see cref="Wallet.LoadFromFile"/>.
 /// </summary>
 /// <remarks>
 /// For the store you can use a <see cref="MemoryBlockStore"/> if you don't care about saving the downloaded data, or a
 /// <see cref="BoundedOverheadBlockStore"/> if you'd like to ensure fast start-up the next time you run the program.
 /// </remarks>
 /// <exception cref="BlockStoreException"/>
 public BlockChain(NetworkParameters @params, Wallet wallet, IBlockStore blockStore)
     : this(@params, new List<Wallet>(), blockStore)
 {
     if (wallet != null)
         AddWallet(wallet);
 }
Esempio n. 43
0
 /// <exception cref="BitCoinSharp.ProtocolException" />
 public GetDataMessage(NetworkParameters @params, byte[] payloadBytes)
     : base(@params, payloadBytes)
 {
 }
Esempio n. 44
0
 /// <exception cref="BitCoinSharp.ProtocolException" />
 public ListMessage(NetworkParameters @params, byte[] bytes)
     : base(@params, bytes, 0)
 {
 }
Esempio n. 45
0
 /// <exception cref="ProtocolException"/>
 public UnknownMessage(NetworkParameters @params, string name, byte[] payloadBytes)
     : base(@params, payloadBytes, 0)
 {
     _name = name;
 }
Esempio n. 46
0
 /// <exception cref="IOException"/>
 /// <exception cref="ProtocolException"/>
 public NetworkConnection(IPAddress inetAddress, NetworkParameters networkParams, uint bestHeight, int connectTimeout)
     : this(new PeerAddress(inetAddress), networkParams, bestHeight, connectTimeout)
 {
 }