Last week, I spent my time developing my first public application — a Telegram bot that functions as a Bitcoin wallet and allows users to 'tip' other group chat participants, as well as make external Bitcoin payments to themselves or others known as 'Lightning Apps'. I assume that the reader is generally familiar with Bitcoin and Telegram, as I will strive to keep it brief without going into details. , and Telegram is a messaging app for mobile devices and PCs that allows users to create their own small applications (chatbots) on its platform.
What are the key features of this application?
- It allows you to reward or encourage a conversation partner with real material value, rather than just "a virtual like", elevating electronic communication to a whole new level.
- A real example of an application that can financially interact with other applications using an open payment protocol.
- All components of the application are open-source projects that can be modified and used for your own purposes. The application does not use closed or commercial solutions, even though it falls under the sphere of e-commerce, which is currently hard to define as open.
And how can this be applied in practice?
Something like this…

or like this…

What do these numbers mean? They are units of Bitcoin — satoshis. Based on exchange rates in mid-2019, 1000 satoshis is approximately $0.06. Satoshis can be spent online or easily exchanged for national currency. For this reason (liquidity), it is not just another "database entry" or "points that you can spend in our partner stores", and real internet money.
*I want to note that some words or phrases I deliberately do not attempt to translate into Russian — either I do not know the contextual translation in some cases, or such a translation, in my opinion, sounds more misleading than correct.
You may wonder how to use such an application if you don't have any bitcoins. They can easily be purchased in small amounts on one of many exchanges or exchange services, or you could get some from a friend who has bitcoins or even receive coins from current bot users. Many mobile wallets offer the option to buy bitcoins directly "on the spot."



Once you have acquired bitcoins (or rather satoshis-s(?)) — launch and make a /deposit.
The bot will then ask how many satoshis you wish to add to your balance and will send you a payment invoice, which can be paid using a mobile wallet by scanning the QR code or clicking the button ("open in wallet") on the invoice page.



After confirming the payment in your wallet, the bot will almost immediately send a payment confirmation, which will be visually displayed in the invoice frame.
Up to this point, we have covered two components of the application — the back-end Telegram bot and the cryptocurrency payment processing system (rather its front-end).
To create the Telegram bot, I used . And of course, the bot itself. .
As for the payment processing system and UX issues, the choice fell (actually, there was almost no choice) on , for which .
If you are looking for direct solutions for handling payment events, it's worth checking out for on-chain payments, and for instant micro-payments (Lightning), solutions like or .
So is it self-hosted or not!?
Yes, it is. In my application, I use free hosting by BTCPayServer — , but it is entirely possible and doesn't take much time to launch your own processing center. However, keep in mind that you'll need about 500GB available on your hard drive to store Bitcoin (and Litecoin) blockchains. You will also require computational and network resources during synchronization and, depending on your needs, necessary "wrappers" for the blockchains to facilitate easy interaction. BTCPayServer does not contain by design private keys or any other information that would allow control over your wallet.
For on-chain (regular) payments, it is necessary to add the so-called xpub wallet key to BTCPayServer to generate receiving addresses (public keys). This makes it possible and secure to use BTCPayServer even in a 'shared' mode. All these xpub keys and addresses can be easily obtained from good wallets like , for further processing setup.
Anyone who has dealt with Bitcoin has heard that Bitcoin is slow and transactions are expensive, especially during hype, which is why for instant micro-payments, it is advisable to use (off-chain) transactions via the Lightning Network.
What is the Lightning Network?
It is somewhat like a plugin to Bitcoin that builds an additional layer of abstraction and allows for instant and virtually free transactions on the Bitcoin network. All of this is made possible by cryptographic magic with multi-signatures, often referred to as smart contract. There are several implementations of the Lightning Network protocol; I use a C implementation.
The main difference between on-chain and off-chain (Lightning) payments is how they are stored. All on-chain transactions are relayed across all nodes in the network until one of the Bitcoin nodes announces that includes the transactions. (There’s even a company called , which manufactures mining hardware). This is why we call such transactions on-chain. Such transactions will be recorded in the public blockchain and will be preserved in it for the entirety of its existence. Additionally, these transactions are publicly accessible and can be monitored, tracked, and analyzed.
In the case of off-chain (Lightning) transactions, everything works differently. Each Lightning network node has one (or more) on-chain addresses—these are the actual Bitcoin addresses from which everything starts. When Bitcoins appear at such an address, it is possible to open a so-called lightning channel. to another node, meaning that using cryptographic techniques, these two nodes have agreed on the availability of funds between themselves. Later, all transactions (both their own and those of external nodes) that go through such a channel are stored only on the nodes of the transaction participants (and intermediary nodes). The only transactions recorded on the blockchain are those related to opening or closing a channel. On a larger scale, this creates a network of interconnected nodes that establishes thousands of different paths for 'pouring' funds from one node to another according to certain strict rules. Almost all such transactions are stored only in the database file of the nodes themselves. This is precisely why we refer to them as off-chain.
The diagram shows a visualization of all components of the application

In brief:
1) The user sends a command to the bot in Telegram
2) Telegram sends a message about the event the Python application the bot
3) the Python application sends a request to BTCPayServer
4) BTCPayServer generates incoming BTC and LTC addresses and also sends a request for an invoice to lightning-charge, which, in turn, communicates with the daemon c-lightning. As a result, we get a beautiful HTML form for processing the payment
5) The user pays the invoice and sees a confirmation
6) BTCPayServer sends an invoice payment notification (IPN) to the specified callback_url, in our case callbacks.py (another Python application for receiving notifications)
7) Based on the received data, the user's balance is updated
… and if the user wants to withdraw funds (the coins they received from others) …
8) The Python application the bot waits for a text or the image of a QR code, and when valid data is received, the payment is made using the utilitypaylightning.py*, which initiates the transaction via c-lightning RPC.

*For the sake of fairness, it should be noted that my wrapper paylightning.py is not quite complete and may return a false negative result in specific scenarios. I recommend in cases close to production
What do we have? Users of our bot can transfer material value within group chats or directly without limits. And that's not all — thanks to the Lightning Network protocol, which is a unified and simplified payment network in some sense, there is now the ability to send the same money received in chat to completely external applications. For example, Telegram has already introduced the first bot for Bitcoin payments — @lntxbot. The 'Unified Balance' allows the use of any of the bots depending on the preferences of a particular group chat (yes, the problem is completely imaginary and the solution is quite useless, but it's about the essence). Transferring balance from one bot to another costs nothing and takes seconds! It is important to note that the creators of these bots have never actually communicated with each other.

It is simply enough to forward a message requesting a deposit from @lntxbot to @atomic_tipbot and voilà!
This is no longer just 'transferring numbers in the database' but a payment between two different, unrelated databases. Thus, several 'LApps' have already been integrated into the bot, among them: and .
What does it mean LApp integration?
Each Lightning Network node is essentially a Bitcoin wallet. It has two balances: on-chain and off-chain. The on-chain balance is necessary for opening new channels and storing funds from closed channels. The off-chain balance is what moves between nodes. The main requirements for a node are to send and receive payments, so each node as software has functions pay and invoice. I will demonstrate how this happens:
user@ln-node:/ % lightning-cli invoice 1000000000 internal_description external_description
{
"payment_hash" : "64c0c8f5f8f708b08487ad1376f3d256f92ccb9606987ba395c2b4193efde5a0",
"expires_at" : 1558709834,
"bolt11" : "lnbc10m1pwdaj72pp5vnqv3a0c7uytppy845fhdu7j2mujejukq6v8hgu4c26pj0hauksqdpqv4u8getjdeskchmyv4ekxunfwp6xjmmwxqyjw5qcqp2rzjqw3qcrp2u3ggke56wrjlstcg76drmfw680cvjum88sl7ja7mpas7xzxz8sqqfecqqyqqqqlgqqqqqqgqjqn8e3ml733dkms2txxldnuwsllwhhkldss73268hdka3e7f083vjhjqurwqrndqd2rcd85pw7vkywnr4dq7yfd59r0g2mw4wzztwr6dcprxzej6"
}
We receive an 'invoice' specification in this case, which is the payment format in the Bitcoin network (and Litecoin, by the way, too). This is a string that contains information about the recipient, the transaction amount, expiration time, etc. Detailed information can be obtained by running decodepay on this string:
user@ln-node: / % lightning-cli decodepay lnbc10m1pwdaj72pp5vnqv3a0c7uytppy845fhdu7j2mujejukq6v8hgu4c26pj0hauksqdpqv4u8getjdeskchmyv4ekxunfwp6xjmmwxqyjw5qcqp2rzjqw3qcrp2u3ggke56wrjlstcg76drmfw680cvjum88sl7ja7mpas7xzxz8sqqfecqqyqqqqlgqqqqqqgqjqn8e3ml733dkms2txxldnuwsllwhhkldss73268hdka3e7f083vjhjqurwqrndqd2rcd85pw7vkywnr4dq7yfd59r0g2mw4wzztwr6dcprxzej6
{
"currency" : "bc",
"created_at" : 1558105034,
"expiry" : 604800,
"payee" : "025a14b8ed40583d67aec92da19453e0b2d1fbbf75f96f85d3dd0ff61a51ee0490",
"msatoshi" : 1000000000,
"amount_msat" : "1000000000msat",
"description" : "external_description",
"min_final_cltv_expiry" : 10,
"routes" : [
[
{
"pubkey" : "03a20c0c2ae4508b669a70e5f82f08f69a3da5da3bf0c973673c3fe977db0f61e3",
"short_channel_id" : "574012x1255x1",
"fee_base_msat" : 1000,
"fee_proportional_millionths" : 1,
"cltv_expiry_delta" : 144
}
]
],
"payment_hash" : "64c0c8f5f8f708b08487ad1376f3d256f92ccb9606987ba395c2b4193efde5a0",
"signature" : "304502210099f31dffd18b6db8296637db3e3a1ffbaf7b7db087a2ad1eedb7639f25e78b25022079038370073681aa1e1a7a05de6588e98ead078896d0a37a15b755c212dc3d37"
}
To pay for such an "invoice," we need the pay function from c-lightning:
user@ln-node: / % lightning-cli pay lnbc2u1pwdana3pp5c0nyfgq974hr8huflt9uutyalj4maaw3q5594xp89jkvw74jme3sdql2pshjgr5dus8q6r0dejjqampd3kx2aqcqzpgwjgn45gy80jwjhgm3tpsxg33j6h6pehdus0mnjerrad943cz3vs83g30lyhlhfjxtqvtl76vttkuhs5jekuxpsqmf98l8265pwmm76gp4e7z6j
{
"id" : 163,
"payment_hash" : "c3e644a005f56e33df89facbce2c9dfcabbef5d105285a98272cacc77ab2de63",
"destination" : "03021c5f5f57322740e4ee6936452add19dc7ea7ccf90635f95119ab82a62ae268",
"msatoshi" : 200000,
"amount_msat" : "200000msat",
"msatoshi_sent" : 200003,
"amount_sent_msat" : "200003msat",
"created_at" : 1558106072,
"status" : "complete",
"payment_preimage" : "1a9552b9f4e9199e26839353f870b12cc85b7674a2fb134e78aa370032611019",
"bolt11" : "lnbc2u1pwdana3pp5c0nyfgq974hr8huflt9uutyalj4maaw3q5594xp89jkvw74jme3sdql2pshjgr5dus8q6r0dejjqampd3kx2aqcqzpgwjgn45gy80jwjhgm3tpsxg33j6h6pehdus0mnjerrad943cz3vs83g30lyhlhfjxtqvtl76vttkuhs5jekuxpsqmf98l8265pwmm76gp4e7z6j"
}
All transaction statuses are handled by the entire network and your own node in particular. There is no need (but you have the option) to interact with the authors of the payment-receiving application or any of their APIs to obtain information about the payment status. There is no need to check the payment status in the processing intermediary's system. You do not need to wait for your transaction to be approved by a bank or government institution. After all, there are no chargebacks and other external factors that can affect the balance in your account. This is a solution for transferring value over the Internet, without the need for a third-party arbiter to determine whether the transaction complies with the rules (sometimes even internal rules that not all participants have been informed about in advance) or not. In Bitcoin, there are no "internal rules." The only rules that need to be followed are the rules of the network — open and well-known.
This makes real direct, practically free and instant money transactions between people or programs completely autonomously.
If you have the ability to obtain payment data from a third-party application, you can interact in a financial sense with that application. For example, consider the service lnsms.world, which allows you to send an SMS message to any number, paying for it with bitcoins. To integrate this application, we just need to pass the data from the web form directly to the SMS sending script — emulating user actions on the website:
payload = {
'number': phone_number,
'text': text,
'force_unicode': 0
}
send_req = requests.post('https://lnsms.world/invoice', data=payload)
if send_req.status_code == 201:
plain_invoice = str(send_req.text)
I don't know why, but lnsms responds with HTTP status code 201 and returns an invoice in the BOLT11 format. Well, that's enough for bot users to make a payment for sending SMS from their balance received in chats. The user doesn't even know what's happening; they just paid a few cents for sending an SMS. And I, as a developer, don't delve into the details of SMS services. I just forwarded the payment and received the service. I can add a markup on top or not — it's my free choice. No accounts, agreements, or another API for trivial tasks like sending SMS.
And now let's imagine for a moment that our application is something more useful than a chatbot and makes a payment not to another bot but to another application or device connected to the Internet. Or it's tens or even hundreds of insignificant payments every second between devices, services, stores, or some service providers. This is the power of micro-payments; this is how the Internet of Things should look. Projects like are already bringing these ideas to life, and soon we will see significant changes, in my opinion, in the field we currently call e-commerce.
If you liked the post and want to see bitcoins in action — .
Only registered users can participate in the survey. , please.
Are you interested in purely technical articles about Bitcoin and related software?
Yes
No
I'm more interested in the market aspects of cryptocurrency.
8 users voted. 4 users abstained.
Source: habr.com
