How I wrote a centralized cryptocurrency in PHP. (Part 1 - Basic notes + Quick start)

About BitcoinRu.org

BitcoinRu.org is a simple, convenient and free online Bitcoin wallet.

Advantages of the BitcoinRu.org online wallet:

  1. The funds are safe and under your full control.
  2. Nobody can block your account.
  3. Open access to private keys.
  4. Completely anonymous Bitcoin Wallet and does not require personal identification.
  5. Fast transactions on the Bitcoin network.
  6. Full control over the commission.
  7. Instant registration of a Bitcoin wallet.

To create a Bitcoin wallet, simply enter your email and password.

Be your own bank, try opening a Bitcoin wallet today.

© 2022 BitcoinRu.org – Bitcoin Wallet in Russian Contact email: [email protected] Support the BTC project: 3HUeVTsa3pw1dNcqY4Tv3Lr9RMdA1WQfxa

Please confirm:

You want to send 0.00 BTC

Below is a copy of the transaction we tried to submit

They previously advised me to come to blockchain. I came, downloaded their scripts, launched it, I needed an API key, filled out a form to request an API key (that’s how they do it now), waited a day, and I received a refusal. Refusal, KARL) I am being denied service in the Bitcoin area. You see, they didn’t like my site, and they think that I don’t need to accept bitcoins. But first of all, what do they care about my site? I wrote them an angry letter, full of hatred, demanding that they give me the key this minute.

What other options are there? What other 100% reliable methods are there, are there any known libraries for working with Bitcoind, for example in PHP, or aggregators, or something else?

Google didn't help me, or I was looking for the wrong thing. Please do not offer various Robocashes, money and Horns and Hoofs, you need to work without commission from such offices.

Have you ever thought about selling your services in exchange for Bitcoin? Today, many major players in the market are already doing this, starting with OkCupid and Khan Academy, ending even with WordPress. In addition, some countries are thinking about Bitcoin as a currency. In this series of lessons, we will get acquainted with the Bitcoin API and Coinbase SDK.

Coinbase SDK

To work with Coinbase, you can use special tools and SDKs that are available to absolutely everyone (with some reservation about the price).

  • Accepting payments using Coinbase is completely free;
  • You agree to pay a fee (1%) if you wish to transfer money to your bank account, but only if your sales exceed $1,000,000 (one million dollars);
  • The minimum transfer amount in the Bitcoin network is 0.001 BTC. Using Coinbase, you can lower this limit to 1 Satoshi (0.00000001 BTC);

Another important point: you can activate the “Instant Exchange” service. This service will convert the Bitcoin payment amount immediately into the currency of your choice without additional steps.

History of the Internet archive, description of the project, awards and blocking

The Wayback Machine is an Internet Archive. Essentially it is a non-profit organization that was founded in 1996. The task of this organization is to collect and store all kinds of public information collected from the Internet: web pages, e-books, photo and video materials. The main servers are located in San Francisco. The size of the archive as of February 2017 is 13 petabytes and includes 525 billion copies of web pages.

Types of Integration

Like many other online payment services, Coinbase offers two main integration options. The first is faster and easier, the second is more complex, but provides advanced features that are more suitable for large projects.

The first option is to use one of Coinbase's tools, namely MerchantTools. You can use buttons, pages and frames. If you use a CMS or e-commerce management system (WordPress, WooCommerce, Magento.), you will probably find many relevant plugins.

The second way is to fully integrate the service, excluding access to Coinbase. In fact, we will be using a specific PHP SDK.

What can we do with this SDK?

  • sell or buy bitcoins (or make currency exchange);
  • send/request bitcoins by email or bitcoin address;
  • accept bitcoin payments as a merchant service;
  • store bitcoins in one or more wallets;
  • have access to a list of operations on bitcoins (blocks, transactions, etc.);
  • process current and micro payments;

There are currently three versions of the SDK: for Ruby, Java and PHP. There are also many unofficial libraries for other languages ​​(Python, .NET, Node.js...). In our case, we will use the PHP SDK, which you can find on GitHub.

Note : Before moving to the next step, you will need to be registered with Coinbase.

Russian Blogs

Reusing the same Bitcoin wallet address is a big privacy issue. If you have a simple e-commerce store or website that requires donations, you may want to consider creating a unique address for each transaction.

There are many payment processors, such as Bitpay, that do all the hard work for you. The downside is that they need to use your private key. However, you can use the Extended Public Key (XPUB) from the Hierarchical Deterministic (HD) wallet to implement your own simple solution.

The whole process in BIP32 explained in. I suggest you read it first to get a general idea of ​​the source of the address.

In this tutorial we will use Electrum,OS X Sierra,Apache 2.4,PHP 7.1 and Bit-Wasp/bitcoin-php。

When it comes to Bitcoin wallets, any HD wallet (like Mycelium) can be used. The installation process should be the same on any UNIX-like system, especially Linux.

The PHP library and its dependencies require PHP5.6+. Open a terminal and check the current version:

php -v

In my environment the output is:

PHP 7.1.0 (cli) (built: Jan 2 2022 20:09:35) (NTS) Copyright (c) 1997-2016 The PHP Group Zend Engine v3.1.0-dev, Copyright (c) 1998-2016 Zend Technologies

If the version is less than 5.6, you must update PHP first.

Install Composer globally

Before installing the bitcoin-php library, we must make sure that composer is installed.

Open a terminal and enter:

composer -V

If its content looks like this: Composer version 1.3.0 2016-12-24 00:47:03 You can safely skip this step.

Otherwise install:

curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/local/bin/composer

Run composer -V again and check if it was installed successfully.

Install Bitcoin PHP library

Go to your web server's document root (the directory where your website is stored) and create a folder:bitcoin/hdkeys。

In my example, the document root is ~/Sites. But on other UNIX-like systems it might be /var/www. If you're not sure, check your server settings.

cd ~/Sites mkdir bitcoin bitcoin/hdkeys cd bitcoin/hdkeys

installBit-Wasp/bitcoin-phpLibrary:

composer require bitwasp/bitcoin

It will download libraries and dependencies. This process may take several minutes.

image

If there are no errors, proceed to the next step.

Generating wallet addresses from xpub, ypux and zpub

I wrote a small class that loads all the necessary bitcoin-php classes and wraps up certain methods for ease of use.

Upload it to the directory:

wget https://gist.githubusercontent.com/mariodian/5b67a1f315a74a7753a6f23d0198ec48/raw/2742a7909dd2621381de53209e85348a078df470/HD.php

First, we need to obtain the extended public key.

Open Electrum, click "Wallet", then click "Primary Public Key" and copy the string.

image

In Electrum 3.x, go to Wallet -> Information -> Master Public Key。

Legacy address(p2pkh)

Open your favorite text editor, create a file called generate.php, then copy and paste the following code:

PHP SDK

Installation

Let's start by installing the library package. On the GitHub page for this SDK you will not find the ability to interact with Composer. However, with a simple search we can find the corresponding coinbase/coinbase package.

To install, place the following code in the composer.json file:

Next, use composer (if you have it installed) to download the library:

Authentication

Before we start writing code, let's talk about authentication. Developers have two authentication options to gain access to the API method. The first is the use of an API key pair and an API Secret. Second, use OAuth2.

The Coinbase documentation is quite clear: if you only intend to interact with your account and make changes to it, you can use the API Key. If you need the user to use his account within your application, then it is best to use OAuth2.

API Key + Secret

Generating an API key is very easy if you have a Coinbase account. All you have to do is go here and click on the “+ New API Key” button.

If this is your first time doing this, you will most likely have to verify your account using Authy.

You should see the following form:

You will need to provide account information and a list of rights that need to be assigned to a specific key. You can also select one or more IP addresses to add to the white list.

To create and activate an API key, first click the “Create” button and then “Enable”.

OAuth 2.0

If you want to use OAuth 2.0, you'll have to go through a simple process first. This time you need to create not an API key, however, but an OAuth 2.0 application. To do this, go to https://coinbase.com/oauth/applications. Next, click on the “+ Create an Application” button:

We take notes into account before development

We will use a double hash verification system using Proof-of-Work. It makes sense to check hashes at the software and network application level. This is due to the process of optimizing the load on the servers. Because when we contact the server to check the hash many times, such a load will appear. Therefore, I propose to do the following:

  1. On a software miner, check the hash locally to ensure that the conditions are satisfied.
  2. When the conditions on the software miner coincide with the necessary ones, we check at the application network level (at the server level).

This is, in my best opinion, the optimal way to distribute the load.
It’s easier to check locally on your computer several times than to spam requests to the server many times. Name - I came up with a simple, and perhaps memorable name - FlyCoin with a three-digit currency code FLC.

Database - I'll use a simple and convenient option, PDO.

Crypto wallets will be generated using GUID and mt_rand, and POSIX time will be used as a seed.

Are you too lazy to make a hash checking function?
— Yes, that’s why I decided to take the code from one old (open source) miner of the (already deceased) Entropy cryptocurrency, my friend Nikita. I can't believe he created only one cryptocurrency.
Is there something else? In general, you can find all of his creations (which sometimes even I use) in his VKontakte group. I hope they are useful to you too.

Receiving information from the Bitcoin network

The most “heavy” point. The classic solution is to raise your own reference Bitcoin full node, also known as canonical bitcoind. This will allow us to communicate with it via JSON-RPC. With it, we will be able to both receive information from the network and push transactions. What you should pay attention to:

  • After installation, node synchronization may take a long time. Only after synchronization the node can be used.
  • It will take up a lot of space. Already 40+ gigabytes.
  • I personally don’t know what kind of request load it can withstand.
  • Any problems with the crash/update will fall on your shoulders.

An alternative is a full node implementation in Ruby+PostgreSQL, Toshi. Non-canonical, but striving for full compatibility implementation. Please note, due to additional indexes, the database will take up 220+ gigabytes of space. Again, synchronization with the network is required. There may be other full node implementations (unknown to me). Another alternative

— use of the provider's public API. Receiving information from the network and broadcasting transactions will fall on his shoulders.

Personally, I recommend connecting several solutions with fallover.

Broadcast transactions

The result of creating and signing transactions is binary data (hex), ready to be pushed into the network. Until the network sees the transaction, consider there is no transaction. When the network sees a transaction, it is considered unconfirmed. The transaction is enough to transfer Bitcoin to one node, after which in a matter of seconds the transaction will be seen by most of the Bitcoin network. Some client nodes from the “Working with Addresses” section (through some of their own hardcoded endpoints), or any full node, can broadcast transactions. You can even broadcast a transaction manually by going to the provider’s special Bitcoin API page and entering the transaction into a special form. Canonically, a confirmed transaction is a transaction included in 6 or more consecutive blocks (or 1-3. Non-canonical, but faster). Transactions with zero (or insufficient) commission may remain unconfirmed for a long time (up to a month, in my experience). It is advisable to periodically retransmit such transactions.

General principles of payment gateway operation

Option 1

Suppose we have a unique invoice (invoice, order) presented to the client for payment, and the client will pay in bitcoins. Let's start by converting the original account currency (USD for example) into BTC. This is a trivial task and we will not consider it. Further. The de facto standard is the generation of a new unique Bitcoin address for each order (aka invoice, aka invoice, aka order). It is expected that only our client will transfer funds to this account, only 1 time, and only a strictly specified amount (more is possible, no one will be offended, but not less). That. When funds arrive at the specified Bitcoin address in the required quantity, the order is considered paid.

Briefly, the chain is like this:

  • order in the system ->
  • generate a unique Bitcoin address corresponding to the order ->
  • show it to the client ->
  • We are waiting for payment to the address ->
  • the order is closed (cancellation upon expiration or receipt of BTC and counting the fact of payment)

When bitcoins arrive at an address, you have options to credit the unconfirmed or confirmed balance. There is a small chance that the transaction will be rolled back, and this could be either due to the fault of the payer (who is actually an attacker) or due to circumstances beyond his control.

If you have the opportunity to “take away” the provided product or service from the client in the event of a reversed transaction, I recommend setting off the unconfirmed balance. This will mean an almost instantaneous payment process for the client (as opposed to an hour of waiting, for example). And if some transactions are found to have been withdrawn in the end, ask the client for a repeat payment, threatening to take away the service/product.

Don’t expect that such fraud will immediately overtake you en masse; transaction rollbacks are very rare, and it is unrealistic to “manually” stimulate such a rollback (for which, by the way, the attacker has no guarantee of success) for technically unsavvy clients (as opposed to chargebacks on credit cards).

Another example when an unconfirmed balance can be counted is if it takes more than one hour to prepare a customer’s order (for example, a customer’s shopping cart is being processed and is being prepared for shipment by a courier service). There is plenty of time to double-check the balance before sending the goods.

For other cases, you can enter a certain threshold, above which you must expect a confirmed balance (for example, 0.25 BTC). For maximum reliability, make it zero.

After closing the order, you can leave the bitcoins at this address until required, or for convenience, transfer them to a single “aggregation” wallet of the merchant. Be careful, in the latter case you can compromise such a commercial indicator as “turnover”, because The payment transaction can be tracked by every paying customer. For transfers, you will need to create, sign and broadcast transactions using the private keys of the addresses.

A few words about the order lifetime.

If your product or service is strictly pegged to its fiat currency equivalent (for example USD), then the typical order lifetime is 7-15 minutes due to exchange rate volatility.

Option 2

Suitable when you do not issue invoices for payment, and the user’s account contains a certain single balance, which he replenishes and from which he spends. Here you will need to generate a Bitcoin address for the user and show it to him, asking him to top up for any amount. In this case, it is necessary to monitor the address for incoming transactions and replenish the user’s internal balance if available. In this case, I recommend counting only confirmed transactions (from 3 blocks and above).

  • generating an address for the user ->
  • monitoring transactions to address ->
  • replenishment of the internal account in the presence of incoming transactions
Rating
( 1 rating, average 4 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]