AboutThis article will describe very easy and safe way to make simple Bitcoin balance calculations
and best approach to store them safely inside MySql (SQL) database, using PHP scripting language.
The ProblemWhenever you are building any Bitcoin web application, you will probably have to store some Bitcoin balances,
and make simple calculations to update them;
and, if you already tried to do this, you will know that using traditional Integers, Big-Integrers, and Floats can cause serious problems.
That is why most developers use Strings and Character arrays.
To implement this they usually choose one of two PHP libraries
BC Math or
GMP.
Although these libraries are great for doing complex operations, they are too heavy for doing simple tasks,
like calculating user balances, which use simple arithmetic.
SolutionTo solve this, I wrote simple PHP Calculator class (
https://github.com/BisonSoft/BigNumber_PHP)
which take two integers represented as strings (without decimal point), and do addition, subtraction, multiplication, division, and modulo operation.
In practice1. To store Bitcoin balances, use strings and store them as Satoshis
5432 BTC store as "154320000"
0.0599 BTC store as "5990000"
2. In MySql define balance column as CHAR rather than VARCHAR, or TEXT, it will improve performance
CHAR(24) is large enough for any practical purposes
Set column DEFAULT option to '0'
3. PHP Calculator classIt accepts strings containing digits only: "12345", "0012345" etc.
Invalid strings will return Error: "-12345", "1.2345" etc.
Dividing with zero will return Error also: "1234" / "0" = "E"
Class takes two stings and returns solution number as string: "1234" + "66" = "1300"
When dividing two numbers, class returns number with decimal point: "87" / "12" = "7.25"
4. SecurityBeside balance column it is wise to set a hash column and to verify balance each time record is accessed.
In this way any corruption to database can be verified.
Sha1 algorithm is sufficient for this
Example:
Balance: "112345500"
Sha1: 1bcd3635438e41be2b0329938f0a55c35f7b6be5