<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arthur G Gordon on Medium]]></title>
        <description><![CDATA[Stories by Arthur G Gordon on Medium]]></description>
        <link>https://medium.com/@arthur.g.gordon?source=rss-1c62f7458f77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x1bc_viIuC_w_Q00</url>
            <title>Stories by Arthur G Gordon on Medium</title>
            <link>https://medium.com/@arthur.g.gordon?source=rss-1c62f7458f77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:24:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arthur.g.gordon/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How To Write Data To The Blockchain]]></title>
            <link>https://medium.com/@arthur.g.gordon/how-to-write-data-to-the-blockchain-846cf6b27ff4?source=rss-1c62f7458f77------2</link>
            <guid isPermaLink="false">https://medium.com/p/846cf6b27ff4</guid>
            <dc:creator><![CDATA[Arthur G Gordon]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 17:07:59 GMT</pubDate>
            <atom:updated>2025-01-30T17:07:59.606Z</atom:updated>
            <content:encoded><![CDATA[<p>This article provides a step by step guide to writing data to the Blockchain.</p><p>The prerequisites to writing data to the blockchain are:</p><ul><li>Git to clone a repository</li><li>Docker to build and run the Containers</li><li>Some confidence with the terminal</li></ul><p>The steps are:</p><ol><li>Clone the Repository</li><li>Build the Application Docker Image</li><li>Start the Overlay Network Docker Compose</li><li>Run the Application Docker Image</li><li>Check System Status</li><li>Create Financing Service Key</li><li>Register Financing Service Key Address with UaaS</li><li>Fund Financing Service Key Address</li><li>Check the Financing Service Address Balance</li><li>Create an Application Key</li><li>Create a Transaction</li><li>Get the Transaction</li></ol><p>These steps are described in the sections below.</p><h3>1. Clone the Repository</h3><p>Use the following command to clone the repository:</p><pre>git clone https://github.com/nchain-innovation/overlay-network</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*Xuvo-6IbTkKWqTIv001i6A.png" /><figcaption>Diagram 1 — System Overview</figcaption></figure><p>As shown in Diagram 1 the repository contains the following components:</p><ul><li><strong>Example Application</strong> — this is the application that writes the transaction to the blockchain</li><li><strong>Financing Service</strong> — provided funding transactions to the Application</li><li><strong>UTXO as a Service (UaaS)</strong> — provides access to the Blockchain for the Application and Financing Service</li></ul><p>For more details about the Financing Service see the previous article</p><p><a href="https://medium.com/@arthur.g.gordon/what-is-a-blockchain-financing-service-and-why-do-i-need-one-377d12e1aa72">What is a Blockchain Financing Service, and Why do I need one?</a></p><p>Note that the repository does not contain any keys, therefore the following steps are about creating and registering the keys with the components:</p><p>6. Create Financing Service Key</p><p>7. Register Financing Service Key Address with UaaS</p><p>8. Fund Financing Service Key Address</p><p>9. Check the Financing Service Address Balance</p><p>10. Create an Application Key</p><p>Once the keys have been created and registered they will be persistently stored, So these steps will only need to be performed once.</p><h3>2. Build the Application Docker Image</h3><p>To build the Application Docker image use the following commands:</p><pre>cd example-app<br>./build.sh<br>cd ..</pre><h3>3. Start the Overlay Network Docker Compose</h3><p>To start the Overlay System use:</p><pre>cd overlay-system<br>docker compose up --detach<br>cd ..</pre><p>To stop the Overlay System use:</p><pre>docker compose down</pre><p>The Overlay System is intended to operate as a service, that is to operate continuously. If you are running it on your computer or laptop it would make sense to stop the Overlay System when you turn off or place your computer in standby, as it may resume in a random state, that is without connections to peers etc.</p><h3>4. Run the Application Docker Image</h3><p>To run the Application Docker image:</p><pre>cd example-app<br>./run.sh<br></pre><p>This should produce the following:</p><pre>INFO:  Started server process [1]<br>INFO:  Waiting for application startup.<br>INFO:  Application startup complete.<br>INFO:  Uvicorn running on http://0.0.0.0:3050 (Press CTRL+C to quit)<br><br></pre><p>This will start a Swagger web server at <a href="http://127.0.0.1:3050/docs">http://127.0.0.1:3050/docs</a></p><p>(depending on configuration) which should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*U2tifCndMFs0UEcPoX6Rog.png" /><figcaption>Diagram 2 — Example Application REST API</figcaption></figure><h3>5. Check System Status</h3><p>Click on the Application Swagger interface, then under `Status`:</p><ol><li>Expand the `Get Status` endpoint.</li><li>Click on the “Try it out” button</li><li>Click on the “Execute” button</li></ol><p>You should see a response similar to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*qul0Eld-sEr-kq851mM4ew.png" /><figcaption>Diagram 3 — Status Response</figcaption></figure><p>Here we are looking for the following:</p><ul><li><strong>Application Status</strong> section — <strong>blockchain_enabled: true</strong></li><li><strong>Financing Service Status</strong> section — <strong>blockchain_status: Connected</strong></li><li><strong>UaaS Status</strong> section — <strong>last block time</strong>: within 30 minutes of the `current_time` provided by the Application status, this means that the UaaS is current with the blockchain.</li></ul><p>If there are any issues with any of the above then either the supporting services are not running or the Application configuration is incorrect.</p><p>The configuration of the Example Application can be found in the <strong>TOML</strong> file /data/example-app.toml. The TOML configuration file also provides information about how to connect to the `Financing Service` and `UTXO as a Service`.</p><h3>6. Create Financing Service Key</h3><p>This section details the process of generating the Financing Service Key. This key will be used by the Financing service to fund the Applications transactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*A5grzjDSnssP3HZavSiuQg.png" /><figcaption>Diagram 4 — Create Financing Service Key</figcaption></figure><p>Click on the Application Swagger interface, then under `Financing Service Admin`:</p><ol><li>Expand the `Add Financing Service Key` endpoint.</li><li>Click on the “Try it out” button.</li><li>Enter a unique `client_id` into the text box.</li><li>Click on the “Execute” button.</li></ol><p>The Response body should show:</p><pre>{<br>&quot;status&quot;: &quot;Success&quot;,<br>&quot;Address&quot;: &quot;mnUyj….kL81vSPsQJdyXRnaQ2Mb38mh2&quot;<br>}</pre><p>This shows the Address associated with the Financing Service Key. Make a note of the Address as it will be used to fund the account.</p><p>This Address can also be obtained using the `Get Address` endpoint, which requests the address from the Financing Service.</p><h3>7. Register Financing Service Key Address with UaaS</h3><p>The Address needs to be registered with UTXO as a Service (UaaS).</p><p>This enables UaaS to track transactions that use this address in the locking script (also known as script pubkey).</p><p>Click on the Application Swagger interface, then under `UTXO as a Service Admin`:</p><ol><li>Expand the `Add Monitor` endpoint.</li><li>Click on the “Try it out” button.</li><li>Enter a `name` and `address` into the text box.</li><li>Click on the `Execute` button.</li></ol><p>The Response body should show:</p><pre>{<br>&quot;status&quot;: &quot;Success&quot;<br>}</pre><p>If you make a mistake you can delete it from the `UaaS` using the `Delete Monitor` endpoint.</p><h3>8. Fund Financing Service Key Address</h3><p>Once the Financing Service Key has been generated it needs to be funded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*NKD7KMMRyZLpXUe126w3Ww.png" /><figcaption>Diagram 5 — Fund Financing Service Address</figcaption></figure><p>Funds are provided by a testnet Faucet, such as:</p><p><a href="https://witnessonchain.com/faucet/tbsv">Faucet | WitnessOnChain</a></p><p>This needs to be provided with the Financing Service Key’s Address, that we obtained from the previous step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*ccLnlC8PR92ItXrC9I3Quw.png" /><figcaption>Diagram 6 — BSV Testnet Faucet</figcaption></figure><p>On the Faucet website:</p><ol><li>Enter the Financing Service Key’s Address into the text box.</li><li>Click on the `Verify you are human` checkbox (if present).</li><li>Click on the `Shoot me the coin` button.</li></ol><p>The Faucet will provide feedback to indicate that the funds were successfully sent.</p><p>It can take a few minutes for the funds to arrive.</p><h3>9. Check the Financing Service Address Balance</h3><p>Click on the Application Swagger interface, then under `Financing Service Admin` section:</p><ol><li>Expand the `Get Balance` endpoint.</li><li>Click on the “Try it out” button.</li><li>Click on the “Execute” button.</li></ol><p>The response should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*kfaOtRh5fSZc2SXWCHSawg.png" /><figcaption>Diagram 7 — Get Balance Response</figcaption></figure><p>This indicates that there are confirmed and/or unconfirmed satoshis associated with this address.</p><p>Confirmed satoshis are satoshis that have been present long enough to be buried under a number of blocks (typically more that 6) so that we can be confident that they will no be subject to a chain reorganization.</p><h3>10. Create an Application Key</h3><p>The Application uses an additional key for its transactions, this is called the Application Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*mn1hOstsc5_OQd5DC0DNeg.png" /><figcaption>Diagram 8 — Create Application Key</figcaption></figure><p>Click on the Application Swagger interface, then:</p><ol><li>Under the `Application Admin` section, expand the `Add Application Key` endpoint.</li><li>Click on the “Try it out” button.</li><li>Click on the “Execute” button.</li></ol><p>The Response body should show:</p><pre>{<br>&quot;status&quot;: &quot;Success&quot;<br>}</pre><p>Now the Application is ready to use!</p><h3>11. Create a Transaction</h3><p>Now we will create a transaction using the Application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*vY3jJl4mSnNIUCTZ-W9GrQ.png" /><figcaption>Diagram 9 — Create Transaction</figcaption></figure><p>Click on the Application Swagger interface, then:</p><ol><li>Under the `Application` section, Expand the `Create Tx` endpoint.</li><li>Click on the “Try it out” button.</li><li>Enter a `data` into the text box (the default is `string`).</li><li>Click on the “Execute” button.</li></ol><p>The Response body should show:</p><pre>{<br>&quot;status&quot;: &quot;Success&quot;,<br>&quot;txid&quot;: &quot;87d8f60ddccdf4f7e221af81fafbe015fc62c5ded94dcffce38f82bfa4ecf361&quot;<br>}<br><br></pre><p>The returned txid is used to get the transaction in the next stage.</p><h3>12. Get the Transaction</h3><p>Then you can use the `txid` to get the transaction using the `Get Tx` endpoint.</p><ol><li>Expand the `Get Tx` endpoint.</li><li>Click on the “Try it out” button.</li><li>Enter the `txid` into the text field.</li><li>Click on the “Execute” button.</li></ol><p>The Response body should show:</p><pre>{<br>  &quot;hash&quot;: &quot;87d8f60ddccdf4f7e221af81fafbe015fc62c5ded94dcffce38f82bfa4ecf361&quot;,<br>  &quot;tx&quot;: {<br> &quot;version&quot;: 1,<br> &quot;vin&quot;: [<br>   {<br>     &quot;prevout&quot;: {<br>       &quot;hash&quot;: &quot;18e30fcbc000192d51c001c5573c5b7eb34a660d47ec2429eb93c559009d460c&quot;,<br>       &quot;n&quot;: 1<br>     },<br>     &quot;scriptSig&quot;: &quot;473044022059223664a70608981da30c6ebd4713e1d164d32f94ca1d3b2aa8079e9e9994ab02203affc3241abe917ed6a67c8368ad9df92fcb8eab4343e18aba930d9c43a23a414121027faa8b6273953eebac242a2944e3e73370ca85b054fbdf0e7aaa9eccc792fde8&quot;,<br>     &quot;sequence&quot;: &quot;ffffffff&quot;<br>   }<br> ],<br> &quot;vout&quot;: [<br>   {<br>     &quot;value&quot;: 0,<br>     &quot;scriptPubKey&quot;: &quot;006a45784170702c737472696e67&quot;,<br>     &quot;spent&quot;: true<br>   }<br> ],<br> &quot;locktime&quot;: 0<br>  }<br>}</pre><p>The transaction can also be found on `WhatsOnChain` testnet explorer</p><p><a href="https://test.whatsonchain.com/">WhatsOnChain.com - BSV Explorer</a></p><p>This website can show the Output as ASCII, this appears as:</p><pre>jExApp,string</pre><p>Where:</p><ul><li>“j” — is an artifact of the OP_0 OP_RETURN</li><li>“ExApp” — is the application name</li><li>“string” — the default text written to the output</li></ul><p>OP_0 OP_RETURN — are the script opcodes to create “False Return” that mark the transaction output as invalid, and allows for data to follow this combination of opcodes.</p><p>These values are the same as the field:</p><pre>&quot;scriptPubKey&quot;: &quot;006a45784170702c737472696e67&quot;,</pre><p>Using an ASCII table such as</p><p><a href="https://www.asciitable.com/">ASCII Table</a></p><p>we get:</p><figure><img alt="Table showing mapping between values in script and meaning/characters" src="https://cdn-images-1.medium.com/max/431/1*u9KhmWACZE4gFHO29-k35w.png" /><figcaption>Hex Digit to Meaning mapping</figcaption></figure><h3>Next Steps</h3><p>Now you have the ability to write data to the blockchain. In a future article we will look at how the application is constructed and how to access the APIs that make it work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=846cf6b27ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Blockchain Financing Service, and Why do I need one?]]></title>
            <link>https://medium.com/@arthur.g.gordon/what-is-a-blockchain-financing-service-and-why-do-i-need-one-377d12e1aa72?source=rss-1c62f7458f77------2</link>
            <guid isPermaLink="false">https://medium.com/p/377d12e1aa72</guid>
            <dc:creator><![CDATA[Arthur G Gordon]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 10:19:46 GMT</pubDate>
            <atom:updated>2024-12-04T10:19:56.202Z</atom:updated>
            <content:encoded><![CDATA[<p>This article explains the purpose of a Financing Service and describes its behaviour as a key supporting component for Blockchain Applications. We also provide a link to the GitHub repository of a Rust implementation of the Financing Service.</p><p>In previous articles we have shown how to build Blockchain Transactions.</p><p><a href="https://medium.com/@arthur.g.gordon/building-blockchain-transactions-with-python-f90aa06cd5f5">Building Blockchain Transactions with Python</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*KRTmIkLjmb4V6hwlxC88_g.png" /><figcaption><strong>Diagram 1 — Transaction Spending and Change</strong></figcaption></figure><p>In the previous article we explained how transactions need to select an unspent transaction output (UTXO) to spend, calculate fees and return the difference as change. This process is shown in Diagram 1 above in which a funding transaction finds a UTXO of 1_000_000 Satoshi and it knows the Application Transaction (Tx) wants 500 Satoshi. Therefore a funding transaction is created with two outputs:</p><ul><li>First output pays 500 Satoshi to the Application provided locking script, to be spent by a future Application Tx</li><li>Second output pays, the change 999_500 minus the fee 50, so 999_450 Satoshi to the Funding locking script to be used in a future funding transaction</li></ul><p>Bitcoin Applications can use transactions to write educational certificates to chain, indicate the validity of an X.509 Certificate via a transaction output being spent or not, or even record zero knowledge proofs on chain. All demonstrations that we have built using the Financing Service.</p><p>All these operations require funding which the Financing Service can generate on demand. This eliminates the need for an Application to manage funding UTXO, calculate change and the associated complexity. By leveraging the Financing Service Blockchain Application development becomes modular as it can utilise a pre-built solution for these tasks.</p><p>Having a separate Financing Service also enables a separate key pair (Private and Public key) to be used for funding transactions from the keys used by the Application itself. This means that the Financing Service does not have access to the Application keys, and if one set of keys are compromised, or need to be updated there is no impact on the other set of keys.</p><p>This approach clearly demonstrates the Separation of Concerns design pattern in which each component addresses a separate concern. This makes the components simpler to maintain, easier to understand, reusable and straightforward to test.</p><h4>Financing Service in Rust</h4><p>We have provided an open source Rust implementation of a Financing Service in the nChain Innovation GitHub repository:</p><p><a href="https://github.com/nchain-innovation/financing-service">GitHub - nchain-innovation/financing-service: The Financing Service is a component that provides funding outpoints for transactions.</a></p><p>This Service can be run natively or from a Docker container and provides a REST API at <a href="http://localhost:8080/status">http://localhost:8080/status</a></p><p>This Service is configured to operate on the BSV blockchain Testnet.</p><h3>Financing Service Use Cases</h3><p>In this section we examine the use cases and functionality provided by the Financing Service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*yN4Ty1SlreQSwcLwYjeXWQ.png" /><figcaption><strong>Diagram 2 — Financing Service Use Cases</strong></figcaption></figure><p>The Client is the Application using the Service, its use cases are:</p><ul><li><strong>Get Status</strong> — returns the current state of the Service, so that the Application can check that the Service is in an operating state</li><li><strong>Request Transaction Fund </strong>— this will provide a funding Transaction</li><li><strong>Get Balance</strong> — Returns the Satoshi balance associated with this Client Address</li><li><strong>Get Address</strong> — Returns the Address of the Client, this is used to top-up the Balance</li></ul><p>A Financing Service is a reusable component that can be used by multiple Applications. Each Application is identified to the Service using a Client Identifier.</p><p>The Admin controls the access to the Service with the following use cases:</p><ul><li><strong>Add Client</strong> — Adds a given Client Identifier and private key to the Service</li><li><strong>Delete Client</strong> — Removes the Client Identifier and private key from the Service</li></ul><p>The Admin is responsible for providing Satoshi for the Service. Notice we have shown this as out of scope of the service in the following use case:</p><ul><li><strong>Top-up Balance</strong> — Add funds to the client Address</li></ul><p>Interestingly the Admin does not need to inform the Service that the Balance has been topped-up as the Service periodically queries the blockchain itself to get each Client’s Balance. This also has the benefit of making the Service stateless, as the Client’s Balances and UTXO (Unspent Transaction Outputs) can all be determined from the Blockchain. This means that the Service has no database storage requirements.</p><h4>Get Status</h4><p>The Get Status call takes no parameters and returns the current state of the Service, so that the Application can check that the Service is in an operating state.</p><p>In our Rust implementation, which provides a REST API the status call returns the following:</p><pre>curl http://127.0.0.1:8080/status<br>{<br> &quot;version&quot;: &quot;1.4.0&quot;,<br> &quot;blockchain_status&quot;: &quot;Connected&quot;,<br> &quot;blockchain_update_time&quot;: &quot;2024-11-05 14:42:29&quot;<br>}</pre><p>Where the fields are:</p><ul><li><strong>Version</strong> — the version of the Financing Service, used to ensure the correct version of the Service is being used, particularly if the Application is dependent on a Feature that is only supported by a particular Service version or above.</li><li><strong>Blockchain_status</strong> — this is the status of the connection between the blockchain and the Service. This can be in one of three states:</li></ul><pre>&quot;Unknown&quot; - the service has just started and has not connected to the Blockchain yet<br>&quot;Failed&quot; - the Service has failed to connect to the blockchain<br>&quot;Connected&quot; - the Service is connected to the blockchain</pre><p><strong>Blockchain_update_time</strong> — the time Service last connected to the blockchain</p><h4>Request Transaction Fund</h4><p>Returns one or more funding transactions based on the request parameters, where the parameters are:</p><ul><li><strong>client_id</strong> — the client id from which these funds will come</li><li><strong>satoshi</strong> — the value in <strong>Satoshi</strong> to be funded</li><li><strong>no_of_outpoints</strong> — the number of funding outpoints to be provided</li><li><strong>multiple_tx</strong> — if there is more than one outpoint they should be in separate txs, the value for this parameter is either <strong>true</strong> or <strong>false</strong></li><li><strong>locking_script</strong> — the locking script to be associated with these outpoints as a hex string</li></ul><p>Example transaction fund request:</p><pre>curl -H &quot;Content-Type: application/json&quot; \<br>  --request POST \<br>  --data &#39;{&quot;client_id&quot;:&quot;client1&quot;,&quot;satoshi&quot;:123,&quot;no_of_outpoints&quot;:1,&quot;multiple_tx&quot;:false,&quot;locking_script&quot;:&quot;000000&quot;}&#39; \<br> http://127.0.0.1:8080/fund</pre><p>In the request above we are asking for 1 outpoint and with the value of 123 Satoshi. What is interesting is that the Client Application provides the locking script, this means that the Service does not have to have access to the Application’s private key, and that the Application can place any script code in the locking script including non Pay to Public Key Hash (P2PKH) transactions.</p><p>Response to request:</p><pre>{<br> &quot;outpoints&quot;:  [{&quot;hash&quot;: &quot;11e1128551854896dba1af5ebd75f7fb712ae88684cae59e86f89b158de86697&quot;, &quot;index&quot;: 1}],<br> &quot;txs&quot;: [{&quot;tx&quot;: &quot;010000000137c36dacc941196a9f773def6e74bc92c8b2952a79178f48b31e4074831c295d000000006a47304402204dde2fda0af07d1c0dc2a22473d1b54065f714405723fdf4a05f27048dc87b770220402ef74c2cc718d83f95a9940f4d489a9931dbbb3eb8d884a38d059e8a63fb2e412102b02cc8307d68c174135fc320a7af3cb4748e14b1701b76f9498ccaf3ffac55efffffffff027f690100000000001976a91404e044fb084b497e20a635bbad95b18506666cbf88ac7b000000000000000300000000000000&quot;<br>}]</pre><p>Notice in the response as well as the outpoint the Service provides the complete transaction. This enables the transaction to be used in signing the Application’s transaction without having to wait for the transaction to be broadcast and captured, speeding up the Application.</p><h4>Transaction Caching</h4><p>As we can see from the above the Financing Service is stateless and does not cache transactions on behalf of the Application.</p><p>The reason for this is that the Application has the best understanding of its requirements for funding transactions and is therefore in the prime position to decide when and how many funding outpoints to request.</p><p>The Application can choose to request funds as required. Alternatively the Application has the option to cache the funding transactions for later use, requesting more funding transactions once the cache hits a minimum threshold.</p><h4>Get Address</h4><p>The Get Address call takes the client id as a parameter and returns the associated Address. This Address can be used to provide more Satoshi for funding transactions.</p><pre>curl http://127.0.0.1:8080/client/client1/address<br>{<br> &quot;address&quot;: &quot;mfxjfLTXLUcCxMDojqRejpfKnF9WhRG5BK&quot;<br>}</pre><h4>Get Balance</h4><p>The Get Address call takes the client id as a parameter and returns the associated Balance in Satoshi.</p><pre>curl http://127.0.0.1:8082/client/client1/balance   <br>{   <br> &quot;confirmed&quot;: 99904,<br> &quot;unconfirmed&quot;: 0<br>}</pre><p>Note that there are two fields in the returned Balance, these are:</p><ul><li><strong>Confirmed</strong> — these are Satoshis that are in transactions that are 6 or more blocks from the tip</li><li><strong>Unconfirmed</strong> — these are Satoshis that are in transactions that are less than 6 blocks from the tip, or are not yet it a block</li></ul><p>For high value transactions Application may wish to only use Satoshi that are considered Confirmed, as these are buried under a large number of blocks so are unlikely to be subject to a block re-organisation.</p><h4>Add Client</h4><p>There are two ways to add a Client to the Financing service. The first is to add it to the configuration file that the service reads on startup. This requires the service to be restarted to re-read the config file.</p><p>The config file is in data/financing-service.toml and the section of interest is:</p><pre>[[client]]<br>client_id = &quot;id1&quot;<br>wif_key = &quot;cW1ciwAgTLs2EGa6cZHpf...kvq72s15rbiUonkrQAhDU4FG&quot;<br><br>[[client]]<br>client_id = &quot;id2&quot;<br>wif_key = &quot;cRJukFhMkntAdZctwcW6.....GTaBTYwcwStRcwh1rqgJdayZa2&quot;</pre><p>Where the fields:</p><ul><li><strong>client_id</strong> — is is how we identify this client</li><li><strong>wif_key</strong> — is the wallet independent format (WIF) of the key used to fund this client’s transactions</li></ul><h4>Add Dynamic Client</h4><p>The alternative to stopping the service and editing the config is to dynamically add the client, via a REST API call:</p><pre>curl -H &quot;Content-Type: application/json&quot; \<br>  --request POST \<br>  --data &#39;{&quot;client_id&quot;:&quot;client15&quot;, \<br>&quot;wif&quot;:&quot;cVLcPuZMfnNNcaU...................oLh3piTnX9WCndRqWh&quot;}&#39; \<br> http://127.0.0.1:8080/client<br><br>{&quot;status&quot;: &quot;Success&quot;}</pre><p>The service will persistently store the client details.</p><h4>Delete Client</h4><p>Again there are two mechanisms for deleting the Client depending on how it was added. Obviously if it was added in the configuration file, then it can be deleted from the configuration file. This will require a restart of the Service.</p><h4>Delete Dynamic Client</h4><p>The second method is to use the REST API to delete a dynamic client, as follows:</p><pre>curl -X DELETE http://127.0.0.1:8080/client/client1<br><br>{&quot;status&quot;: &quot;Success&quot;}</pre><h3>Security</h3><p>This section covers the security considerations when deploying the Financing Service. These include:</p><ul><li><strong>Access to endpoints</strong> — probably one of the simplest measures would be to ensure that only the Applications that should have access to the Service endpoints have access to them.</li><li><strong>Access to configuration </strong>— As the configuration contains the private key in Wallet Independent Format (WIF) there is a risk to the key if the configuration can be read by others. it can be made more secure by placing it in an environment variable, which can be injected by the environment at runtime. The environment variable FS_CONFIG, is read before any attempt is made to read the config file. The config in FS_CONFIG should be in JSON format.</li><li><strong>Client id names</strong> — using unique non-guessable Client ids will help the security of the Service. That is don’t use client1, client2 as we have in this document. Particularly if sharing a Financing Service with others.</li></ul><p>Further stages of security, which are beyond the scope of this article, include:</p><ul><li>Hosting the key in a secret store, such as Docker Secrets. But Docker Secrets are part of a swarm configuration. Kubernetes also provides support for Secrets.</li><li>Ideally the key would be held in a Hardware Security Module (HSM), that supports the Secp256K1 elliptic curve, and the transaction signing performed inside the HSM. AWS provides CouldHSM and Key Management Services (KMS) depending on your security requirements.</li></ul><h3>Summary</h3><p>In this article we have covered the purpose of the Financing Service, as well as the key design decisions and operating details.</p><p>We hope you find the Financing Service as valuable in your Blockchain Application development as we have found it in our work at nChain Research. The Service’s ability to simplify funding transactions has proven indispensable in our development efforts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377d12e1aa72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Do Miners Validate Transactions?]]></title>
            <link>https://medium.com/@arthur.g.gordon/how-do-miners-validate-transactions-ff9321b54c23?source=rss-1c62f7458f77------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff9321b54c23</guid>
            <dc:creator><![CDATA[Arthur G Gordon]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 11:04:42 GMT</pubDate>
            <atom:updated>2024-11-08T11:04:42.989Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here we examine the process of signing a transaction and how the Bitcoin miner uses this signature to validate the transaction.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IFRDcwnzplv2TiAU" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung?utm_source=medium&amp;utm_medium=referral">Daniel K Cheung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article follows on from “Building Blockchain Transactions in Python” which stepped through the process of constructing and broadcasting a transaction.</p><p><a href="https://medium.com/@arthur.g.gordon/building-blockchain-transactions-with-python-f90aa06cd5f5">Building Blockchain Transactions with Python</a></p><p>Note the code in this article is also provided as a Jupyter notebook to make it easier to follow, see here</p><p><a href="https://github.com/nchain-innovation/build-tx-example/blob/main/validate_tx.ipynb">build-tx-example/validate_tx.ipynb at main · nchain-innovation/build-tx-example</a></p><h3>Transaction Signing</h3><p>In the previous article we signed the transaction tx as follows:</p><pre>&gt;&gt;&gt; input_to_sign = 0<br>&gt;&gt;&gt; signed_tx = my_wallet.sign_tx(input_to_sign, fund_tx, tx)<br> &gt;&gt;&gt; signed_tx<br>PyTx { version: 1, tx_ins: [PyTxIn { prev_tx: &quot;d261d1388e5a77119b6d6efb41d3610eb363750056895f4043c8cc7899f4cb17&quot;, prev_index: 0, sequence: 4294967295, <br>script_sig: &quot;0x3045022100aacb290ed3aeb43fc91a179d6a3ffef4c5efcca612c901c719e198c2ee685e2702200505bd74db673c6d723a141bd8ac469327ea4bb7987110042f23f8c3d7f91e3d41 0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43&quot; }], <br>tx_outs: [PyTxOut { amount: 1000, script_pubkey: &quot;OP_DUP OP_HASH160 0x4d7eb7ce5ce099dd218383f3f81d3c2f1e48113f OP_EQUALVERIFY OP_CHECKSIG&quot; }, PyTxOut { amount: 98800, script_pubkey: &quot;OP_DUP OP_HASH160 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53 OP_EQUALVERIFY OP_CHECKSIG&quot; }], locktime: 0 }</pre><p>The signing method returned a complete new transaction, with an additional field <strong>script_sig,</strong> containing bitcoin script which has been completed by the signing operation. The <strong>script_sig</strong> contains two large numbers, these are the transaction <strong>signature</strong> and <strong>public key</strong>.</p><h4>Bitcoin Script</h4><p>The Bitcoin scripting language is based on Forth, a stack-oriented language. This means that values are pushed on the stack, and then operators pop the values off the stack. Once the operation is complete it pushes the result back onto the stack. For example the script:</p><pre> &gt; 1 2 OP_ADD</pre><p>Will push the numbers 1 and 2 onto the stack and the OP_ADD will take the top two numbers from the stack, add them together and push the result (3) to the top of the stack. We can do this using <strong>tx-engine</strong>:</p><pre>&gt;&gt;&gt; from tx_engine import Script, Context<br>&gt;&gt;&gt; s = Script.parse_string(&quot;1 2 OP_ADD&quot;)<br>&gt;&gt;&gt; c = Context(script=s)<br>&gt;&gt;&gt; c.evaluate()<br>True<br>&gt;&gt;&gt; c.get_stack()<br>[3]</pre><p>Note c.evaluate() returns True as the bitcoin script is valid.</p><p>The conditions for script to be valid are:</p><ul><li>nothing in the script triggers failure</li><li>and the top stack item is non-zero (representing True), when the script exits</li></ul><p>A full list of Bitcoin SV script operations can be found, here:</p><p><a href="https://wiki.bitcoinsv.io/index.php/Opcodes_used_in_Bitcoin_Script">Opcodes used in Bitcoin Script</a></p><p>Note that Bitcoin SV (or BSV) supports additional operations over other Bitcoin Blockchains, this increases BSV’s utility for complex scripts, such as validating zero-knowledge proofs.</p><h3>Transaction Validation</h3><p>The <strong>script_sig</strong> script is also known as the <strong>unlocking script</strong>, and the <strong>script_pubke</strong>y as the <strong>locking script</strong>. This indicates how the two scripts operate together. The signing process places data in the <strong>script_sig</strong> (unlocking script) that will unlock the previous transaction’s <strong>script_pubkey</strong> (locking script).<br>In summary a <strong>script_pubkey</strong> is a challenge that the <strong>script_sig</strong> must provide data to unlock. Looking at our funding transaction, which was provided to the signing process, we have:</p><pre><br>&gt;&gt;&gt; fund_txid = &quot;86dc8d65e46bcab2ce44f9820b552b62707e9495e8caad6e3277689168526d2f&quot;<br>&gt;&gt;&gt; fund_tx_as_hex_str = woc_interface.get_raw_transaction(fund_txid)<br>&gt;&gt;&gt; fund_tx = Tx.parse_hexstr(fund_tx_as_hex_str)<br>&gt;&gt;&gt; fund_tx<br><br>PyTx { version: 1, tx_ins: [PyTxIn { prev_tx: &quot;d261d1388e5a77119b6d6efb41d3610eb363750056895f4043c8cc7899f4cb17&quot;, prev_index: 0, sequence: 4294967295, <br>script_sig: &quot;0x3045022100aacb290ed3aeb43fc91a179d6a3ffef4c5efcca612c901c719e198c2ee685e2702200505bd74db673c6d723a141bd8ac469327ea4bb7987110042f23f8c3d7f91e3d41 0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43&quot; }], <br>tx_outs: [PyTxOut { amount: 1000, <br>script_pubkey: &quot;OP_DUP OP_HASH160 0x4d7eb7ce5ce099dd218383f3f81d3c2f1e48113f OP_EQUALVERIFY OP_CHECKSIG&quot; }, <br>PyTxOut { amount: 98800, <br>script_pubkey: &quot;OP_DUP OP_HASH160 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53 OP_EQUALVERIFY OP_CHECKSIG&quot; }], locktime: 0 }</pre><p>So what do these script operations, in <strong>script_pubkey</strong>, do:</p><ul><li><strong>OP_DUP</strong> ( n — — n n) Duplicates the top stack item</li><li><strong>OP_HASH160</strong> (n — — hash) Hashes the top stack item with SHA-256 and RIPEMD-160 hash functions</li><li><strong>OP_EQUALVERIFY</strong> (x y — -) This checks that the top two stack items are equal, if not the script exits and marks the transaction as invalid</li><li><strong>OP_CHECKSIG</strong> (sig pubkey — -) The signature is checked against the hashed transaction and the provided signature and public key</li></ul><p>By decoding the combined script_sig (unlocking script) and script_pubkey (locking script) we can see:</p><pre>script_sig (unlocking script)<br>1) Starting stack [] (where left is the top of the stack)<br><br>2) 0x3045022100aacb290ed3aeb43fc91a179d6a3ffef4c5efcca612c901c719e198c2ee685e2702200505bd74db673c6d723a141bd8ac469327ea4bb7987110042f23f8c3d7f91e3d41<br>[signature]<br><br>3) 0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43<br>[public_key signature]<br><br><br>Script_pubkey (locking script)<br>4) OP_DUP <br>[public_key public_key signature]<br><br>5) OP_HASH160<br>[hash(public_key) public_key signature]<br><br>6) 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53<br>[0x7b…e1 hash(public_key) public_key signature]<br><br>7) OP_EQUALVERIFY (this could quit with False at this point)<br>[public_key signature]<br><br>8) OP_CHECKSIG<br>[] True</pre><p>Note that the script_sig (unlocking script) takes the hash of the public key, hence this is known as a Pay 2 Public Key Hash (P2PKH) transaction. This is one of the most commonly found transactions in Bitcoin.</p><h4>Transaction Validation in Python</h4><p>To validate this transaction the miner will first take the <strong>script_sig</strong>, from the transaction. In this case from our broadcast transaction:</p><pre><br>&gt;&gt;&gt; own_txid = &#39;72f201f87e3bb42bbd7f8eaed0f555a268a0eba5d0fb101160167c758ed863bb&#39;<br>&gt;&gt;&gt; own_tx_as_hex_str = woc_interface.get_raw_transaction(own_txid)<br>&gt;&gt;&gt; own_tx = Tx.parse_hexstr(own_tx_as_hex_str)<br>&gt;&gt;&gt; own_tx<br>PyTx { version: 1, tx_ins: [PyTxIn { prev_tx: &quot;86dc8d65e46bcab2ce44f9820b552b62707e9495e8caad6e3277689168526d2f&quot;, prev_index: 1, sequence: 4294967295, <br>script_sig: &quot;0x3045022100b09f980d91842499a82b696279d9f1590b7e31cef600ea0b60c41bd10e5b2f87022079a7a65e3090779a789de8892eac36aff5220e8c81d948c86dc61ebb7c08eb9441 <br>0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43&quot; }], <br>tx_outs: [PyTxOut { amount: 1000, script_pubkey: &quot;OP_DUP OP_HASH160 0x4d7eb7ce5ce099dd218383f3f81d3c2f1e48113f OP_EQUALVERIFY OP_CHECKSIG&quot; }, PyTxOut { amount: 97700, script_pubkey: &quot;OP_DUP OP_HASH160 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53 OP_EQUALVERIFY OP_CHECKSIG&quot; }], locktime: 0 }</pre><p>The <strong>sig_script</strong> will place the <strong>signature</strong> and <strong>public key</strong> on the stack:</p><pre>&gt;&gt;&gt; script_sig = Script.parse_string(<br>&quot;0x3045022100b09f980d91842499a82b696279d9f1590b7e31cef600ea0b60c41bd10e5b2f87022079a7a65e3090779a789de8892eac36aff5220e8c81d948c86dc61ebb7c08eb9441<br> 0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43&quot;)</pre><p>The miner will then take the <strong>script_pubkey</strong>, from the funding transaction:</p><pre> &gt;&gt;&gt; script_pubkey = Script.parse_string(<br>&quot;OP_DUP OP_HASH160 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53 OP_EQUALVERIFY OP_CHECKSIG&quot;)</pre><p>The miner evaluates <strong>sig_script</strong> and takes the resultant stack. The miner then passes this stack (with the <strong>signature</strong> and <strong>public key</strong>) to the <strong>script_pubkey</strong> which is then evaluated, if this returns true the transaction script is valid.</p><p>For the purposes of this exercise the operation will be simplified to combining the two scripts, as follows:</p><pre>&gt;&gt;&gt; combined_script = script_sig + script_pubkey</pre><p>Then before we execute the scripts we will need to calculate the <strong>signature hash (sig_hash)</strong> of the transaction to provide to the <strong>OP_CHECKSIG</strong> operation. The miner will perform a similar operation to calculate the <strong>sig_hash</strong> (z) and provide it to the <strong>OP_CHECKSIG</strong> operation.</p><pre>&gt;&gt;&gt; from tx_engine import sig_hash, SIGHASH<br>&gt;&gt;&gt; z = sig_hash(own_tx, 0, script_pubkey, 98800, SIGHASH.ALL_FORKID)</pre><p>Given the <strong>sig_hash</strong> function arguments:</p><p>* own_tx — Spending transaction</p><p>* 0 — Spending input index in the spending transaction</p><p>* script_pubkey — The lock_script of the output being spent</p><p>* 98800 — The satoshi amount in the output being spent</p><p>* SIGHASH.ALL_FORKID — Sighash flag</p><p>The ALL_FORKID flag is a combination of SIGHASH_ALL and SIGHASH_FORKID where:</p><ul><li>SIGHASH_ALL means sign all inputs and outputs</li><li>SIGHASH_FORKID indicates that this is a BSV transaction</li></ul><p>For further details of sighash flags see:</p><p><a href="https://wiki.bitcoinsv.io/index.php/SIGHASH_flags">SIGHASH flags</a></p><p>The transaction hash (z) is then provided to the execution Context, which then evaluates the combined script:</p><pre>&gt;&gt;&gt; x = Context(script=combined_script, z=z)<br>&gt;&gt;&gt; x.evaluate()<br>True</pre><p><strong>Good work!</strong> you have just validated your first transaction.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff9321b54c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Blockchain Transactions with Python]]></title>
            <link>https://medium.com/@arthur.g.gordon/building-blockchain-transactions-with-python-f90aa06cd5f5?source=rss-1c62f7458f77------2</link>
            <guid isPermaLink="false">https://medium.com/p/f90aa06cd5f5</guid>
            <dc:creator><![CDATA[Arthur G Gordon]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 16:14:11 GMT</pubDate>
            <atom:updated>2024-10-29T16:14:11.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>This article provides a step-by-step guide to building blockchain transactions in Python.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8NSIcoJDI9s5pyvj" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung?utm_source=medium&amp;utm_medium=referral">Daniel K Cheung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Note the code in this article is provided as a <strong>Jupyter</strong> <strong>notebook</strong> to make it easier to follow, see here:</p><p><a href="https://github.com/nchain-innovation/build-tx-example/blob/main/build_tx.ipynb">https://github.com/nchain-innovation/build-tx-example/blob/main/build_tx.ipynb</a></p><p>As with most software engineering, being hands on helps build a deeper understanding of what is going on. In this case, understanding the capability of transactions and the <strong>Forth</strong>-based scripting language they employ. This language can be used to validate transaction signatures, embed data and even verify <strong>zero knowledge proofs</strong> as my colleagues have demonstrated here:</p><p><a href="https://medium.com/@w.zhang/snark-verification-on-a-bitcoin-mainnet-c467991d931c">https://medium.com/@w.zhang/snark-verification-on-a-bitcoin-mainnet-c467991d931c</a></p><p>Note the term ‘transaction’ is often abbreviated as ‘tx’. I’ll use both terms interchangeably throughout this article.</p><p>The steps to create a transaction (tx) are:</p><ol><li><strong>Generate a wallet keypair</strong></li><li><strong>Fund the wallet keypair</strong></li><li><strong>Create the Transaction</strong></li><li><strong>Broadcast the Tx</strong></li></ol><p>The <strong>BSV blockchain</strong> also has the following networks:</p><ul><li><strong>Mainnet</strong> — Used for real world applications that need the blockchain guarantees of being persistent.</li><li><strong>Testnet</strong> — Used for testing transactions, there is no guarantee that this blockchain will be maintained and transactions may be lost over time.</li><li><strong>STN</strong> — Used for performance testing of blockchain infrastructure.</li></ul><p>In this case we will be using <strong>BSV Testnet</strong>. The current status of BSV Testnet can be seen by going to the <strong>WhatsOnChain</strong> website</p><p><a href="https://test.whatsonchain.com/">https://test.whatsonchain.com/</a></p><p>From the <strong>WhatsOnChain</strong> website we can see the latest blocks, their block height and current age.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*b1mnqGtrtkyfEqe2FHA7NA.png" /><figcaption>Diagram 1 — WhatsOnChain Blocks</figcaption></figure><p>By clicking on a block, we can view the transactions it contains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/955/1*zv7GpKSHBjuplDlzHLne9Q.png" /><figcaption>Diagram 2 — WhatsOnChain Transactions in a Block</figcaption></figure><p>Note that each transaction has a transaction id, or <strong>txid</strong>, which is a unique identifier created from the hash of the transaction.</p><h3>Generate a Wallet Keypair</h3><p>The wallet keypair is composed of a private and public key. These keys are associated with funds in the blockchain. The public key enables others to send funds to you. The private key is used to sign the transaction to demonstrate that you are entitled to the funds in that tx input, hence why this key should be protected.</p><p>For this we will use the <strong>tx-engine</strong> library from <strong>PyPi</strong></p><p><a href="https://pypi.org/project/tx-engine/">https://pypi.org/project/tx-engine/</a></p><p>To install the library use:</p><pre>pip install tx-engine</pre><p>The <strong>tx-engine</strong> library has a <strong>Wallet</strong> class which provides the key generation and handling functions that we require.</p><pre>% python3<br>&gt;&gt;&gt; from tx_engine import Wallet<br>&gt;&gt;&gt; my_wallet = Wallet.generate_keypair(&quot;BSV_Testnet&quot;)</pre><p>This generates a wallet containing a unique keypair.</p><pre>&gt;&gt;&gt; my_wallet.to_wif()<br>‘cNqYa1cV7vbz1GLt6fCxgM143y……L7tTJBQ5EhtJ133QWoxU9’</pre><p>The <strong>to_wif</strong>() method exports the private key in Wallet Independent Format (WIF). Keep this string as it is used to import the private key into this or another wallet. Note that as this is the private key it should be kept secret (and not placed in your GitHub repository etc.).</p><pre>&gt;&gt;&gt; my_wallet.get_address()<br>‘mro6fhFv852664upXfugUCMPHnVNbEohKp’</pre><p>The <strong>address</strong> is the public key hashed and displayed in base58 format. The network it is intended for is represented by the first letter at the start of the address (in this case ‘m’ (or ’n’) for testnet).</p><h3>Fund the Wallet Keypair</h3><p>Some BSV developers generously provide Faucets for funding <strong>BSV Testnet</strong> transactions, for this article we have used:</p><p><a href="https://witnessonchain.com/faucet/tbsv">https://witnessonchain.com/faucet/tbsv</a></p><p><a href="https://witnessonchain.com/faucet/tbsv">Faucet | WitnessOnChain</a></p><p>This Faucet requires your wallet address (in our example mro6fhFv852664upXfugUCMPHnVNbEohKp) to know where to send the funding satoshi to. Once you press the “shoot me the coin” button the funds will be sent as a transaction which you can find on <strong>WhatsOnChain</strong> by searching by your address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*Dm0F-nKfHD6wYsxNLncZIw.png" /><figcaption>Diagram 3 — WhatsOnChain Funding Transaction with one input and one output</figcaption></figure><p>Make a note of the transaction id (txid) and the index of the output that is sent to your address.</p><p>This faucet produced a tx with one input and one output, at the time of writing, so the index will be 0.</p><p>From the diagram we can see:</p><ul><li>Input was 0.001 BSV, where 1 BSV is 100,000,000 satoshi, so the input is 100,000 satoshi.</li><li>Under the tx output we can see the value as 0.0099904 so 99,904 satoshi.</li></ul><p>So what happened to the difference between the input and output 100,00–99,904 = 96 satoshi?</p><p>This value was used to fund the transaction and is allocated to the miner for including the transaction in a block to be mined. Transaction fees are based on the size, in bytes, of the transaction. For small transactions approximately 100 satoshi should be sufficient on BSV Testnet.</p><p>So in summary the tx fee is calculated by:</p><pre>tx_fee = input_value - output_value</pre><h3>Create Tx</h3><p>In this case we will build a transaction to pay 1,000 satoshi back to the funding Faucet</p><p>The tx_engine has the following classes to help construct and decode transactions:</p><ul><li><strong>TxIn</strong> — the tx input</li><li><strong>TxOut </strong>— the tx output</li><li><strong>Tx</strong> — represents a full transaction</li></ul><h4>TxIn</h4><p>The transaction input provides the funds for this transaction.The transaction input, TxIn constructor takes the parameters:</p><ul><li><strong>prev_tx</strong> — the transaction id (txid) of the funding transaction</li><li><strong>prev_index </strong>— the index of the transaction output that we are spending (note tx indexes start at 0)</li></ul><p>This is where the tx from the Faucet comes into play. By noting the txid and index of the funding transaction we can generate a tx input using:</p><pre>&gt;&gt;&gt; from tx_engine import Tx, TxIn, TxOut<br>&gt;&gt;&gt; vins = [TxIn(prev_tx=&quot;5c866b70189008586….93dcca4d3a1b701e3786566f819450eca9ba&quot;, <br>prev_index=0)]</pre><p>Note that we have put the input into an array which we will be using in the transaction later.</p><h4>TxOut</h4><p>The output declares where we want the funds to go, which is 1,000 to the Faucet and the rest to the newly generated public key, minus the fee for the transaction, say 104 satoshi.</p><p>So we had 99,904 satoshi in and we will get 99,904 — (1000 + 104) = 98,800 satoshi as the remainder.</p><pre>&gt;&gt;&gt; from tx_engine import p2pkh_script, address_to_public_key_hash</pre><p>Start by importing a couple of helper functions</p><ul><li><strong>Address_to_public_key_hash </strong>— this takes an address and returns a public key hash (as required by <strong>p2pkh_script</strong>)</li><li><strong>p2pkh_script</strong> — this takes a hash of a public key and returns a pay to public key hash (P2PKH) script, this is the most common script for payment on BSV</li></ul><p>So we will create two outputs for our transaction, the first will pay back to The witness on chain Faucet address (mnai8LzKea5e3C9qgrBo7JHgpiEnHKMhwR).</p><pre>&gt;&gt;&gt; vouts = []<br>&gt;&gt;&gt; faucet_addr = &quot;mnai8LzKea5e3C9qgrBo7JHgpiEnHKMhwR&quot;<br>     <br>&gt;&gt;&gt; locking_script = p2pkh_script(address_to_public_key_hash(faucet_addr))<br>&gt;&gt;&gt; vouts.append(TxOut(amount=1000, script_pubkey=locking_script))</pre><p>We can examine the <strong>locking_script</strong> code by typing:</p><pre>&gt;&gt;&gt; locking_script<br>OP_DUP OP_HASH160 0x4d7eb7ce5ce099dd218383f3f81d3c2f1e48113f OP_EQUALVERIFY OP_CHECKSIG</pre><p>Now you can pay yourself the remainder using the <strong>Wallet</strong> method <strong>get_locking_script</strong>() to provide a P2PKH script to pay to your address.</p><pre>&gt;&gt;&gt; vouts.append(TxOut(amount=98800, script_pubkey=my_wallet.get_locking_script()))</pre><h4>Tx</h4><p>Now we assemble the transaction by placing the inputs and outputs in a transaction as follows:</p><pre>&gt;&gt;&gt; tx = Tx(version=1, tx_ins=vins, tx_outs=vouts, locktime=0)</pre><p>We can see that the transaction has a <strong>version</strong> field. Most transactions use version 1, there have been <strong>BIP</strong> (Bitcoin Improvement Proposal) that have associated other version numbers with special behaviour (See <strong>BIP68</strong>, <strong>BIP112</strong>).</p><p>The <strong>locktime</strong> defines the earliest time that a transaction is valid. In our case we want the transaction to be processed as soon as possible so we set this to 0.</p><h4>Signing the Transaction</h4><p>The next stage is to sign the transaction. This demonstrates that you have the private key associated with the p2pkh script of the output of the previous/funding transaction.</p><p>To sign the transaction we need access to data from the funding transaction, which we will get using the <strong>WhatsOnChain</strong>’s API, which is setup as follows:</p><pre>&gt;&gt;&gt; from tx_engine import WoCInterface<br> <br>&gt;&gt;&gt; woc_interface = WoCInterface()<br>&gt;&gt;&gt; config = {“network_type”: “testnet”}<br>&gt;&gt;&gt; woc_interface.set_config(config)</pre><p>Now to get the funding transaction we use the <strong>get_raw_transaction</strong> method with the <strong>txid</strong> of the funding tx, this returns the transaction in hex string format.</p><pre>&gt;&gt;&gt; funding_tx = woc_interface.get_raw_transaction(“e11d8bbd69db4d6…a68fae9c22054d0”)<br>&gt;&gt;&gt; funding_tx<br>&#39;010000000184dae2675b22df71193ba6e0eddb1344fee9c77b877969e222c8f10adc53b07a130000006a47304402204a6cd4349c598d41960d53daa03c8ef6be603c1258671639f9df562915d4b4ba022015fdb2f6af587f3600bd8069ff0d8764af459c1de8c19c526051ae47fef7e33141210292acdb57c788c1e8c83cdb0ae8f23e079139ba7ba1bccf67b31653c7af12c4b4ffffffff0140860100000000001976a9147bb7074e3ee92db046fd13752b665de27175cde188ac00000000&#39;</pre><p>Note that if you get a <strong>SSLError</strong> or <strong>SSLCertVerificationError</strong> exception on calling <strong>get_raw_transaction</strong> you may have a VPN/Firewall in place that prevents direct access to the <strong>WhatsOnChain</strong> API (‘api.whatsonchain.com’). Contact your IT Support to see if they can provide a fix.</p><p>The <strong>parse_hexstr</strong> method takes the hex string and returns the transaction in <strong>Tx</strong> format, which is required for signing the transaction we will broadcast.</p><pre>&gt;&gt;&gt; fund_tx = Tx.parse_hexstr(funding_tx)<br>&gt;&gt;&gt; fund_tx<br>PyTx { version: 1, tx_ins: [PyTxIn { prev_tx: &quot;7ab053dc0af1c822e26979877bc7e9fe4413dbede0a63b1971df225b67e2da84&quot;, prev_index: 19, sequence: 4294967295, script_sig: &quot;0x304402204a6cd4349c598d41960d53daa03c8ef6be603c1258671639f9df562915d4b4ba022015fdb2f6af587f3600bd8069ff0d8764af459c1de8c19c526051ae47fef7e33141 0x0292acdb57c788c1e8c83cdb0ae8f23e079139ba7ba1bccf67b31653c7af12c4b4&quot; }], tx_outs: [PyTxOut { amount: 99904, script_pubkey: &quot;OP_DUP OP_HASH160 0x7bb7074e3ee92db046fd13752b665de27175cde1 OP_EQUALVERIFY OP_CHECKSIG&quot; }], locktime: 0 }</pre><p>The following signs the transaction tx, given the input to sign (0), the funding transaction and tx. If successful it returns a new signed transaction (signed_tx).</p><pre>&gt;&gt;&gt; input_to_sign = 0<br>&gt;&gt;&gt; signed_tx = my_wallet.sign_tx(input_to_sign, fund_tx, tx)<br>&gt;&gt;&gt; signed_tx<br>PyTx { version: 1, tx_ins: [PyTxIn { prev_tx: &quot;d261d1388e5a77119b6d6efb41d3610eb363750056895f4043c8cc7899f4cb17&quot;, prev_index: 0, sequence: 4294967295, script_sig: &quot;0x3045022100aacb290ed3aeb43fc91a179d6a3ffef4c5efcca612c901c719e198c2ee685e2702200505bd74db673c6d723a141bd8ac469327ea4bb7987110042f23f8c3d7f91e3d41 0x03dcf21dbdbaa744333af236c3382c85d6308e6d05599df5d3cb19e0f19a205d43&quot; }], tx_outs: [PyTxOut { amount: 1000, script_pubkey: &quot;OP_DUP OP_HASH160 0x4d7eb7ce5ce099dd218383f3f81d3c2f1e48113f OP_EQUALVERIFY OP_CHECKSIG&quot; }, PyTxOut { amount: 98800, script_pubkey: &quot;OP_DUP OP_HASH160 0xd86625de492d8bd8bbc4930f2bef4328e37f1f53 OP_EQUALVERIFY OP_CHECKSIG&quot; }], locktime: 0 }</pre><p>Finally you have a complete transaction which you can now broadcast to the network!</p><p>Note that we can see the results of the signing operation in the <strong>script_sig</strong> section of the input, we will describe how this works with the <strong>script_pubkey</strong> in another article.</p><h3>Broadcast the Transaction</h3><p>To broadcast the transaction we will use the <strong>WhatsOnChain</strong> API <strong>broadcast_tx</strong> method. This returns the <strong>txid</strong> if successful or an error message if not.</p><pre>&gt;&gt;&gt; result = woc_interface.broadcast_tx(signed_tx.serialize().hex())<br>&gt;&gt;&gt; result.status_code<br>200<br> <br>&gt;&gt;&gt; result.json()<br>&#39;72f201f87e3bb42bbd7f8eaed0f555a268a0eba5d0fb101160167c758ed863bb&#39;</pre><p><strong>Congratulations</strong> you have now broadcast your first transaction!</p><p>If you want to check that the <strong>txid</strong> is the same as that of the transaction that was sent, use the following <strong>id</strong>() method on the transaction. This call returns the <strong>txid</strong> of the transaction.</p><pre> &gt;&gt;&gt; signed_tx.id()<br> &#39;72f201f87e3bb42bbd7f8eaed0f555a268a0eba5d0fb101160167c758ed863bb&#39;</pre><p>The <strong>txid</strong> can be used to find the transaction in <strong>WhatsOnChain</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*hbXhv11FCzuif6iKERj9-g.png" /><figcaption>Diagram 4 — WhatsOnChain Broadcast Transaction</figcaption></figure><p>From the screen shot we can see that we have created a transaction with one input and two outputs</p><h3>Summary</h3><p>Well done, if you have got this far you have created and funded a wallet and transaction which has now been broadcast on the network and will be mined into a block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xu2EUYeeEmiPzlbY" /><figcaption>Photo by <a href="https://unsplash.com/@danielkcheung?utm_source=medium&amp;utm_medium=referral">Daniel K Cheung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Stay tuned for future articles which will describe what is going on in the script and how to perform more complex operations using blockchain transactions and scripts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f90aa06cd5f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>