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: 
113: 
114: 
115: 
116: 
//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

    // Or create your own:
    // let builder = NetworkBuilder()
    // builder.CopyFrom(Network.Main)
    // builder.SetName("MyBlockChain").BuildAndRegister()

// 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("5JACYRvADrPzrzFNoGMUsV8UJYTsNbswaZWxjDT2GuMAUYGfG3w", network)

let bobPublic = 
    //bob.ScriptPubKey
    // or use existing:
    BitcoinAddress.Create("117GQHu6kUJSudEZSv7Bjv4FbK5ZBCgBy", network)
    
let builder = TransactionBuilder()
let transaction =
    let sum = Money.Coins 0.0001m
    let fee = Money.Coins 0.00002m
    let coin = 
        Coin(
            OutPoint(
                // Previous Transaction-ID, get it from your wallet.
                new uint256("86dfe9fd88e3ee7024c9fa36ec8a47845e591c14d7c7913150877a269ab4f8dc"), 
                // Coin-order-number
                1
            ), TxOut(sum, tuomas.ScriptPubKey)
        ) :> ICoin
    builder
        .AddCoins([|coin|])
        .AddKeys(tuomas)
        .Send(bobPublic, (sum - fee))
        .SendFees(fee)
        .SetChange(tuomas.GetAddress())
        .BuildTransaction(true)
    
let ``check if transaction is valid``() =
    let hash = transaction.GetHash()
    let isOk, errs = builder.Verify(transaction)
    hash, isOk, errs
    
// You can broadcast it e.g. from http://blockr.io
let transactionToBroadcast = transaction.ToHex()


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

/// Connect to public Bitcoin network:
#if INTERACTIVE
let node = 
#else
use node = 
#endif
    // get a bit-node server address, e.g. from: https://bitnodes.21.co/
    // Not all the nodes work.
    let n = Node.Connect(network, "81.109.119.97:8333")
    n.VersionHandshake()
    n

// Channel for getting back messages
let getListener() = node.CreateListener()

// Do the trade
let sendSync() =
    // Notify server
    node.SendMessage(new InvPayload(transaction)) 
    System.Threading.Thread.Sleep 1000
    // Send transaction
    node.SendMessage(new TxPayload(transaction))
    System.Threading.Thread.Sleep 4000
    node.Disconnect()
    
//let sendAsync() =
//    async {
//        do! node.SendMessageAsync(new InvPayload(transaction)) 
//            |> Async.AwaitTask
//        do! Async.Sleep 1000
//        do! node.SendMessageAsync(new TxPayload(transaction)) 
//            |> Async.AwaitTask
//        do! Async.Sleep 4000
//        node.DisconnectAsync()
//    }
//sendAsync() |> Async.Start
//

Console.WriteLine "Press any key"
Console.ReadLine() |> ignore
0

// 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 newWallet : unit -> Key

Full name: Script.newWallet
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 alice : BitcoinSecret

Full name: Script.alice
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 bob : BitcoinSecret

Full name: Script.bob
val tuomas : BitcoinSecret

Full name: Script.tuomas
val bobPublic : BitcoinAddress

Full name: Script.bobPublic
Multiple items
type BitcoinAddress =
  inherit Base58Data
  new : base58:string * ?expectedNetwork:Network -> BitcoinAddress + 2 overloads
  member GetScriptAddress : unit -> BitcoinScriptAddress
  member ScriptPubKey : Script
  member ToColoredAddress : unit -> BitcoinColoredAddress
  static member Create : base58:string * ?expectedNetwork:Network -> BitcoinAddress

Full name: NBitcoin.BitcoinAddress

--------------------
BitcoinAddress(base58: string, ?expectedNetwork: Network) : unit
BitcoinAddress(id: TxDestination, network: Network) : unit
BitcoinAddress(rawBytes: byte [], network: Network) : unit
BitcoinAddress.Create(base58: string, ?expectedNetwork: Network) : BitcoinAddress
val builder : TransactionBuilder

Full name: Script.builder
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 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
BitcoinSecret.GetAddress() : BitcoinPubKeyAddress
val ( check if transaction is valid ) : unit -> uint256 * bool * Policy.TransactionPolicyError []

Full name: Script.( check if transaction is valid )
val hash : uint256
Transaction.GetHash() : uint256
val isOk : 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 transactionToBroadcast : string

Full name: Script.transactionToBroadcast
Transaction.ToHex() : string
val node : Node

Full name: Script.node


 Connect to public Bitcoin network:
val n : Node
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
val getListener : unit -> NodeListener

Full name: Script.getListener
Node.CreateListener() : NodeListener
val sendSync : unit -> unit

Full name: Script.sendSync
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
type Console =
  static member BackgroundColor : ConsoleColor with get, set
  static member Beep : unit -> unit + 1 overload
  static member BufferHeight : int with get, set
  static member BufferWidth : int with get, set
  static member CapsLock : bool
  static member Clear : unit -> unit
  static member CursorLeft : int with get, set
  static member CursorSize : int with get, set
  static member CursorTop : int with get, set
  static member CursorVisible : bool with get, set
  ...

Full name: System.Console
Console.WriteLine() : unit
   (+0 other overloads)
Console.WriteLine(value: string) : unit
   (+0 other overloads)
Console.WriteLine(value: obj) : unit
   (+0 other overloads)
Console.WriteLine(value: uint64) : unit
   (+0 other overloads)
Console.WriteLine(value: int64) : unit
   (+0 other overloads)
Console.WriteLine(value: uint32) : unit
   (+0 other overloads)
Console.WriteLine(value: int) : unit
   (+0 other overloads)
Console.WriteLine(value: float32) : unit
   (+0 other overloads)
Console.WriteLine(value: float) : unit
   (+0 other overloads)
Console.WriteLine(value: decimal) : unit
   (+0 other overloads)
Console.ReadLine() : string
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
Next Version Raw view Test code New version

More information

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