2 people like it.

BTC transfers with NBitcoin

Bitcoin transfers. I'm not responsible if your money gets lost. Have fun!

  1: 
  2: 
  3: 
  4: 
  5: 
  6: 
  7: 
  8: 
  9: 
 10: 
 11: 
 12: 
 13: 
 14: 
 15: 
 16: 
 17: 
 18: 
 19: 
 20: 
 21: 
 22: 
 23: 
 24: 
 25: 
 26: 
 27: 
 28: 
 29: 
 30: 
 31: 
 32: 
 33: 
 34: 
 35: 
 36: 
 37: 
 38: 
 39: 
 40: 
 41: 
 42: 
 43: 
 44: 
 45: 
 46: 
 47: 
 48: 
 49: 
 50: 
 51: 
 52: 
 53: 
 54: 
 55: 
 56: 
 57: 
 58: 
 59: 
 60: 
 61: 
 62: 
 63: 
 64: 
 65: 
 66: 
 67: 
 68: 
 69: 
 70: 
 71: 
 72: 
 73: 
 74: 
 75: 
 76: 
 77: 
 78: 
 79: 
 80: 
 81: 
 82: 
 83: 
 84: 
 85: 
 86: 
 87: 
 88: 
 89: 
 90: 
 91: 
 92: 
 93: 
 94: 
 95: 
 96: 
 97: 
 98: 
 99: 
100: 
101: 
102: 
103: 
104: 
105: 
106: 
107: 
108: 
109: 
110: 
111: 
112: 
//Add reference to NBitcoin
#if INTERACTIVE
#I "./../packages/NBitcoin.3.0.1.6/lib/net45/"
#I "./../packages/Newtonsoft.Json.9.0.1/lib/net45"
#r "NBitcoin.dll"
#r "Newtonsoft.Json.dll"
#endif

open System
open NBitcoin
open NBitcoin.Protocol

// --------------- CREATING A TRANSACTION --------------- // 

let network = 
    // Select your network
    Network.Main
    // Network.Test

/// Generate a new wallet private key for a new user as byte array
let getNewPrivateKey() = Key().ToBytes()

/// Create BitcoinSecret from byte array
let getSecret(bytes:byte[]) = BitcoinSecret(Key(bytes), network)

// Create a new wallet:
let newWallet() = Key()
let alice = BitcoinSecret(newWallet(), network)
let bob = BitcoinSecret(newWallet(), network)
    
// You can also use existing wallets.
// to test you can create wallets e.g. in https://rushwallet.com/
let tuomas = BitcoinSecret("5J3RWPbfuR3W8sQkPto15CBWgc99SiMBNvP7KYb9xdAUW35L2qh", network)

let bobPublic = 
    //bob.GetAddress()
    // or use existing:
    BitcoinPubKeyAddress("1PnfqAxqmH9r5ADc9xCoaXJRjcuFs2xh1H", network)
    
let transaction =
    let sum = Money.Coins 0.008m
    let fee = Money.Coins 0.0004m
    let coin = 
        Coin(
            OutPoint(
                // Previous Transaction-ID, get it from your wallet.
                new uint256("70c3a3925d6a6d652f9a2f4c5b0a93c93c783c9939d701e3a1b24fce6b2244b9"), 
                // Coin-order-number
                0 // (Inside a transaction can be many operations, you have to spot your coin.)
            ), TxOut(sum, tuomas.ScriptPubKey)
        ) :> ICoin
    let builder = TransactionBuilder()
    let tx = 
        builder
            .AddCoins([|coin|])
            .AddKeys(tuomas)
            .Send(bobPublic, (sum - fee))
            .SendFees(fee)
            .SetChange(tuomas.GetAddress())
            .BuildTransaction(true)

    let ok, errs = builder.Verify tx
    match ok with
    | true -> tx
    | false -> failwith(String.Join(",", errs))

// --------------- SENDING TRANSACTION TO SERVER --------------- // 

// Do the trade
let sendSync() =
    /// Connect to public Bitcoin network:
    // get a bit-node server address, e.g. from: https://bitnodes.21.co/
    // Not all the nodes work.
    use node = Node.Connect(network, "81.17.27.134:8333")
    node.VersionHandshake()
    // Notify server
    node.SendMessage(InvPayload(transaction)) 
    System.Threading.Thread.Sleep 1000
    // Send transaction
    node.SendMessage(TxPayload(transaction))
    System.Threading.Thread.Sleep 5000
    node.Disconnect()
    transaction.GetHash()
//sendSync()

//let sendAsync() =
//    async {
//        use node = Node.Connect(network, "81.17.27.134:8333")
//        node.VersionHandshake()
//        do! node.SendMessageAsync(InvPayload(transaction)) 
//            |> Async.AwaitTask
//        do! Async.Sleep 1000
//        do! node.SendMessageAsync(TxPayload(transaction)) 
//            |> Async.AwaitTask
//        do! Async.Sleep 5000
//        node.DisconnectAsync()
//        Console.WriteLine (transaction.GetHash())
//    }
//sendAsync() |> Async.Start

// Instead of sending, you can broadcast the 
// transaction manually e.g. from http://blockr.io
let transactionToBroadcast = transaction.ToHex()

// You can search the transaction 
// e.g. from: https://blockchain.info/
let hash = transaction.GetHash()

// Some resources:
// Open book: https://programmingblockchain.gitbooks.io/programmingblockchain/content/
// A video: https://www.youtube.com/watch?v=X4ZwRWIF49w
// Article: https://www.codeproject.com/articles/835098/nbitcoin-build-them-all
namespace System
namespace NBitcoin
namespace NBitcoin.Protocol
val network : Network

Full name: Script.network
type Network =
  val _MagicBytes : byte[]
  member AlertPubKey : PubKey
  member Consensus : Consensus
  member CreateAssetId : base58:string -> BitcoinAssetId
  member CreateBase58Data : type:Base58Type * base58:string -> Base58Data
  member CreateBitcoinAddress : base58:string -> BitcoinAddress + 1 overload
  member CreateBitcoinExtKey : key:ExtKey -> BitcoinExtKey + 1 overload
  member CreateBitcoinExtPubKey : pubkey:ExtPubKey -> BitcoinExtPubKey
  member CreateBitcoinScriptAddress : base58:string -> BitcoinScriptAddress
  member CreateBitcoinSecret : base58:string -> BitcoinSecret + 1 overload
  ...

Full name: NBitcoin.Network
property Network.Main: Network
val getNewPrivateKey : unit -> byte []

Full name: Script.getNewPrivateKey


 Generate a new wallet private key for a new user as byte array
Multiple items
type Key =
  new : unit -> Key + 2 overloads
  member Derivate : cc:byte[] * nChild:uint32 * ccChild:byte[] -> Key
  member GetBitcoinSecret : network:Network -> BitcoinSecret
  member GetEncryptedBitcoinSecret : password:string * network:Network -> BitcoinEncryptedSecretNoEC
  member GetWif : network:Network -> BitcoinSecret
  member IsCompressed : bool with get, set
  member PubKey : PubKey
  member ReadWrite : stream:BitcoinStream -> unit
  member ScriptPubKey : Script
  member Sign : hash:uint256 -> ECDSASignature + 1 overload
  ...

Full name: NBitcoin.Key

--------------------
Key() : unit
Key(fCompressedIn: bool) : unit
Key(data: byte [], ?count: int, ?fCompressedIn: bool) : unit
val getSecret : bytes:byte [] -> BitcoinSecret

Full name: Script.getSecret


 Create BitcoinSecret from byte array
val bytes : byte []
Multiple items
val byte : value:'T -> byte (requires member op_Explicit)

Full name: Microsoft.FSharp.Core.Operators.byte

--------------------
type byte = Byte

Full name: Microsoft.FSharp.Core.byte
Multiple items
type BitcoinSecret =
  inherit Base58Data
  new : key:Key * network:Network -> BitcoinSecret + 1 overload
  member Copy : compressed:Nullable<bool> -> BitcoinSecret
  member Encrypt : password:string -> BitcoinEncryptedSecret
  member GetAddress : unit -> BitcoinPubKeyAddress
  member IsCompressed : bool
  member PrivateKey : Key
  member PubKey : PubKey
  member PubKeyHash : KeyId
  member ScriptPubKey : Script
  member Type : Base58Type

Full name: NBitcoin.BitcoinSecret

--------------------
BitcoinSecret(key: Key, network: Network) : unit
BitcoinSecret(base58: string, ?expectedAddress: Network) : unit
val newWallet : unit -> Key

Full name: Script.newWallet
val alice : BitcoinSecret

Full name: Script.alice
val bob : BitcoinSecret

Full name: Script.bob
val tuomas : BitcoinSecret

Full name: Script.tuomas
val bobPublic : BitcoinPubKeyAddress

Full name: Script.bobPublic
Multiple items
type BitcoinPubKeyAddress =
  inherit BitcoinAddress
  new : base58:string * ?expectedNetwork:Network -> BitcoinPubKeyAddress + 1 overload
  member Hash : KeyId
  member Type : Base58Type
  member VerifyMessage : message:string * signature:string -> bool

Full name: NBitcoin.BitcoinPubKeyAddress

--------------------
BitcoinPubKeyAddress(base58: string, ?expectedNetwork: Network) : unit
BitcoinPubKeyAddress(keyId: KeyId, network: Network) : unit
val transaction : Transaction

Full name: Script.transaction
val sum : Money
Multiple items
type Money =
  new : satoshis:int -> Money + 4 overloads
  member Abs : unit -> Money
  member Almost : amount:Money * dust:Money -> bool + 1 overload
  member CompareTo : other:Money -> int + 1 overload
  member Equals : other:Money -> bool + 1 overload
  member GetHashCode : unit -> int
  member Satoshi : int64 with get, set
  member Split : parts:int -> IEnumerable<Money>
  member ToDecimal : unit:MoneyUnit -> decimal
  member ToString : unit -> string + 1 overload
  ...

Full name: NBitcoin.Money

--------------------
Money(satoshis: int) : unit
Money(satoshis: uint32) : unit
Money(satoshis: int64) : unit
Money(satoshis: uint64) : unit
Money(amount: decimal, unit: MoneyUnit) : unit
Money.Coins(coins: decimal) : Money
val fee : Money
val coin : ICoin
Multiple items
type Coin =
  new : unit -> Coin + 5 overloads
  member Amount : Money with get, set
  member CanGetScriptCode : bool
  member GetHashVersion : unit -> HashVersion
  member GetScriptCode : unit -> Script
  member Outpoint : OutPoint with get, set
  member ScriptPubKey : Script with get, set
  member ToColoredCoin : asset:AssetMoney -> ColoredCoin + 2 overloads
  member ToScriptCoin : redeemScript:Script -> ScriptCoin
  member TxOut : TxOut with get, set

Full name: NBitcoin.Coin

--------------------
Coin() : unit
Coin(txOut: IndexedTxOut) : unit
Coin(fromOutpoint: OutPoint, fromTxOut: TxOut) : unit
Coin(fromTx: Transaction, fromOutputIndex: uint32) : unit
Coin(fromTx: Transaction, fromOutput: TxOut) : unit
Coin(fromTxHash: uint256, fromOutputIndex: uint32, amount: Money, scriptPubKey: Script) : unit
Multiple items
type OutPoint =
  new : unit -> OutPoint + 5 overloads
  member Equals : obj:obj -> bool
  member GetHashCode : unit -> int
  member Hash : uint256 with get, set
  member IsNull : bool
  member N : uint32 with get, set
  member ReadWrite : stream:BitcoinStream -> unit
  member ToString : unit -> string
  static member Parse : str:string -> OutPoint
  static member TryParse : str:string * result:OutPoint -> bool

Full name: NBitcoin.OutPoint

--------------------
OutPoint() : unit
OutPoint(outpoint: OutPoint) : unit
OutPoint(hashIn: uint256, nIn: uint32) : unit
OutPoint(hashIn: uint256, nIn: int) : unit
OutPoint(tx: Transaction, i: uint32) : unit
OutPoint(tx: Transaction, i: int) : unit
Multiple items
type uint256 =
  new : unit -> uint256 + 5 overloads
  member AsBitcoinSerializable : unit -> MutableUint256
  member Equals : obj:obj -> bool
  member GetByte : index:int -> byte
  member GetHashCode : unit -> int
  member GetLow32 : unit -> uint32
  member GetLow64 : unit -> uint64
  member GetSerializeSize : ?nType:int * ?protocolVersion:ProtocolVersion -> int
  member Size : int
  member ToBytes : ?lendian:bool -> byte[]
  ...
  nested type MutableUint256

Full name: NBitcoin.uint256

--------------------
uint256() : unit
uint256(b: uint256) : unit
uint256(b: uint64) : unit
uint256(str: string) : unit
uint256(vch: byte []) : unit
uint256(vch: byte [], ?lendian: bool) : unit
Multiple items
type TxOut =
  new : unit -> TxOut + 2 overloads
  member GetDustThreshold : minRelayTxFee:FeeRate -> Money
  member IsDust : minRelayTxFee:FeeRate -> bool
  member IsTo : destination:IDestination -> bool
  member ReadWrite : stream:BitcoinStream -> unit
  member ScriptPubKey : Script with get, set
  member Value : Money with get, set
  static member Parse : hex:string -> TxOut

Full name: NBitcoin.TxOut

--------------------
TxOut() : unit
TxOut(value: Money, destination: IDestination) : unit
TxOut(value: Money, scriptPubKey: Script) : unit
property BitcoinSecret.ScriptPubKey: Script
type ICoin =
  member Amount : IMoney
  member CanGetScriptCode : bool
  member GetHashVersion : unit -> HashVersion
  member GetScriptCode : unit -> Script
  member Outpoint : OutPoint
  member TxOut : TxOut

Full name: NBitcoin.ICoin
val builder : TransactionBuilder
Multiple items
type TransactionBuilder =
  new : unit -> TransactionBuilder + 1 overload
  member AddCoins : [<ParamArray>] coins:ICoin[] -> TransactionBuilder + 2 overloads
  member AddKeys : [<ParamArray>] keys:ISecret[] -> TransactionBuilder + 1 overload
  member AddKnownRedeems : [<ParamArray>] knownRedeems:Script[] -> TransactionBuilder
  member AddKnownSignature : pubKey:PubKey * signature:TransactionSignature -> TransactionBuilder + 1 overload
  member BuildTransaction : sign:bool -> Transaction + 1 overload
  member Check : tx:Transaction -> TransactionPolicyError[] + 2 overloads
  member CoinFinder : Func<OutPoint, ICoin> with get, set
  member CoinSelector : ICoinSelector with get, set
  member CombineSignatures : [<ParamArray>] transactions:Transaction[] -> Transaction
  ...

Full name: NBitcoin.TransactionBuilder

--------------------
TransactionBuilder() : unit
TransactionBuilder(seed: int) : unit
val tx : Transaction
BitcoinSecret.GetAddress() : BitcoinPubKeyAddress
val ok : bool
val errs : Policy.TransactionPolicyError []
TransactionBuilder.Verify(tx: Transaction) : bool
TransactionBuilder.Verify(tx: Transaction, errors: byref<Policy.TransactionPolicyError []>) : bool
TransactionBuilder.Verify(tx: Transaction, expectedFeeRate: FeeRate) : bool
TransactionBuilder.Verify(tx: Transaction, expectedFees: Money) : bool
TransactionBuilder.Verify(tx: Transaction, expectedFeeRate: FeeRate, errors: byref<Policy.TransactionPolicyError []>) : bool
TransactionBuilder.Verify(tx: Transaction, expectedFees: Money, errors: byref<Policy.TransactionPolicyError []>) : bool
val failwith : message:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.failwith
Multiple items
type String =
  new : value:char -> string + 7 overloads
  member Chars : int -> char
  member Clone : unit -> obj
  member CompareTo : value:obj -> int + 1 overload
  member Contains : value:string -> bool
  member CopyTo : sourceIndex:int * destination:char[] * destinationIndex:int * count:int -> unit
  member EndsWith : value:string -> bool + 2 overloads
  member Equals : obj:obj -> bool + 2 overloads
  member GetEnumerator : unit -> CharEnumerator
  member GetHashCode : unit -> int
  ...

Full name: System.String

--------------------
String(value: nativeptr<char>) : unit
String(value: nativeptr<sbyte>) : unit
String(value: char []) : unit
String(c: char, count: int) : unit
String(value: nativeptr<char>, startIndex: int, length: int) : unit
String(value: nativeptr<sbyte>, startIndex: int, length: int) : unit
String(value: char [], startIndex: int, length: int) : unit
String(value: nativeptr<sbyte>, startIndex: int, length: int, enc: Text.Encoding) : unit
String.Join(separator: string, values: Collections.Generic.IEnumerable<string>) : string
String.Join<'T>(separator: string, values: Collections.Generic.IEnumerable<'T>) : string
String.Join(separator: string, [<ParamArray>] values: obj []) : string
String.Join(separator: string, [<ParamArray>] value: string []) : string
String.Join(separator: string, value: string [], startIndex: int, count: int) : string
val sendSync : unit -> uint256

Full name: Script.sendSync
val node : Node


 Connect to public Bitcoin network:
type Node =
  member ActualTransactionOptions : TransactionOptions
  member AddSupportedOptions : inventoryType:InventoryType -> InventoryType
  member Advertize : bool with get, set
  member Behaviors : NodeBehaviorsCollection
  member ConnectedAt : DateTimeOffset with get, set
  member Counter : PerformanceCounter
  member CreateListener : unit -> NodeListener
  member Disconnect : unit -> unit + 1 overload
  member DisconnectAsync : unit -> unit + 1 overload
  member DisconnectReason : NodeDisconnectReason with get, set
  ...
  nested type NodeConnection

Full name: NBitcoin.Protocol.Node
Node.Connect(network: Network, endpoint: Net.IPEndPoint, parameters: NodeConnectionParameters) : Node
Node.Connect(network: Network, endpoint: NetworkAddress, parameters: NodeConnectionParameters) : Node
Node.Connect(network: Network, endpoint: string, parameters: NodeConnectionParameters) : Node
Node.Connect(network: Network, ?parameters: NodeConnectionParameters, ?connectedEndpoints: Net.IPEndPoint [], ?getGroup: Func<Net.IPEndPoint,byte []>) : Node
Node.Connect(network: Network, addrman: AddressManager, ?parameters: NodeConnectionParameters, ?connectedEndpoints: Net.IPEndPoint []) : Node
Node.Connect(network: Network, endpoint: Net.IPEndPoint, ?myVersion: ProtocolVersion, ?isRelay: bool, ?cancellation: Threading.CancellationToken) : Node
Node.Connect(network: Network, endpoint: string, ?myVersion: ProtocolVersion, ?isRelay: bool, ?cancellation: Threading.CancellationToken) : Node
Node.VersionHandshake(?cancellationToken: Threading.CancellationToken) : unit
Node.VersionHandshake(requirements: NodeRequirement, ?cancellationToken: Threading.CancellationToken) : unit
Node.SendMessage(payload: Payload, ?cancellation: Threading.CancellationToken) : unit
Multiple items
type InvPayload =
  inherit Payload
  new : unit -> InvPayload + 4 overloads
  member GetEnumerator : unit -> IEnumerator<InventoryVector>
  member Inventory : List<InventoryVector>
  member ReadWriteCore : stream:BitcoinStream -> unit
  member ToString : unit -> string

Full name: NBitcoin.Protocol.InvPayload

--------------------
InvPayload() : unit
InvPayload([<ParamArray>] transactions: Transaction []) : unit
InvPayload([<ParamArray>] blocks: Block []) : unit
InvPayload([<ParamArray>] invs: InventoryVector []) : unit
InvPayload(type: InventoryType, [<ParamArray>] hashes: uint256 []) : unit
namespace System.Threading
Multiple items
type Thread =
  inherit CriticalFinalizerObject
  new : start:ThreadStart -> Thread + 3 overloads
  member Abort : unit -> unit + 1 overload
  member ApartmentState : ApartmentState with get, set
  member CurrentCulture : CultureInfo with get, set
  member CurrentUICulture : CultureInfo with get, set
  member DisableComObjectEagerCleanup : unit -> unit
  member ExecutionContext : ExecutionContext
  member GetApartmentState : unit -> ApartmentState
  member GetCompressedStack : unit -> CompressedStack
  member GetHashCode : unit -> int
  ...

Full name: System.Threading.Thread

--------------------
Threading.Thread(start: Threading.ThreadStart) : unit
Threading.Thread(start: Threading.ParameterizedThreadStart) : unit
Threading.Thread(start: Threading.ThreadStart, maxStackSize: int) : unit
Threading.Thread(start: Threading.ParameterizedThreadStart, maxStackSize: int) : unit
Threading.Thread.Sleep(timeout: TimeSpan) : unit
Threading.Thread.Sleep(millisecondsTimeout: int) : unit
Multiple items
type TxPayload =
  inherit BitcoinSerializablePayload<Transaction>
  new : unit -> TxPayload + 1 overload

Full name: NBitcoin.Protocol.TxPayload

--------------------
TxPayload() : unit
TxPayload(transaction: Transaction) : unit
Node.Disconnect() : unit
Node.Disconnect(reason: string, ?exception: exn) : unit
Transaction.GetHash() : uint256
val transactionToBroadcast : string

Full name: Script.transactionToBroadcast
Transaction.ToHex() : string
val hash : uint256

Full name: Script.hash

More information

Link:http://fssnip.net/7RT
Posted:5 years ago
Author:Tuomas Hietanen
Tags: btc , bitcoin , blockchain