2019-10-17 15:04:50 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package stripecoinpayments_test
|
|
|
|
|
|
|
|
import (
|
satellite/payments: chore to migrate big.Float values out of db
All code on known satellites at this moment in time should know how to
populate and use the new numeric columns on the
stripecoinpayments_tx_conversion_rates and coinpayments_transactions
tables in the satellite db. However, there are still gob-encoded
big.Float values in the database from before these columns existed. To
get rid of those values, so that we can excise the gob-decoding code
from the relevant sections, however, we need something to read the gob
bytestrings and convert them to numeric values, a few at a time, until
they're all gone.
To accomplish that, this change adds two chores to be run in the
satellite core process- one for the coinpayments_transactions table, and
one for the stripecoinpayments_tx_conversion_rates table. They should
run relatively infrequently, so that we do not impose any undue load on
processing resources or the db.
Both of these chores work without using explicit sql transactions, but
should still be concurrent-safe, since they work by way of
compare-and-swap type operations.
If the satellite core process needs to be restarted, both of these
chores will start scanning for migrateable rows from the beginning of
the id space again. This is not ideal, but shouldn't be a problem (as
far as I can tell, there are only a few thousand rows at most in either
of these tables on any production satellite).
Change-Id: I733b7cd96760d506a1cf52735f598c6c3aa19735
2021-10-29 14:32:59 +01:00
|
|
|
"context"
|
2019-10-23 13:04:54 +01:00
|
|
|
"encoding/base64"
|
2020-07-14 14:04:38 +01:00
|
|
|
"errors"
|
satellite/payments: chore to migrate big.Float values out of db
All code on known satellites at this moment in time should know how to
populate and use the new numeric columns on the
stripecoinpayments_tx_conversion_rates and coinpayments_transactions
tables in the satellite db. However, there are still gob-encoded
big.Float values in the database from before these columns existed. To
get rid of those values, so that we can excise the gob-decoding code
from the relevant sections, however, we need something to read the gob
bytestrings and convert them to numeric values, a few at a time, until
they're all gone.
To accomplish that, this change adds two chores to be run in the
satellite core process- one for the coinpayments_transactions table, and
one for the stripecoinpayments_tx_conversion_rates table. They should
run relatively infrequently, so that we do not impose any undue load on
processing resources or the db.
Both of these chores work without using explicit sql transactions, but
should still be concurrent-safe, since they work by way of
compare-and-swap type operations.
If the satellite core process needs to be restarted, both of these
chores will start scanning for migrateable rows from the beginning of
the id space again. This is not ideal, but shouldn't be a problem (as
far as I can tell, there are only a few thousand rows at most in either
of these tables on any production satellite).
Change-Id: I733b7cd96760d506a1cf52735f598c6c3aa19735
2021-10-29 14:32:59 +01:00
|
|
|
"fmt"
|
|
|
|
"math/big"
|
|
|
|
"math/rand"
|
|
|
|
"sort"
|
2020-02-13 18:08:45 +00:00
|
|
|
"sync"
|
2019-10-17 15:04:50 +01:00
|
|
|
"testing"
|
2019-10-23 13:04:54 +01:00
|
|
|
"time"
|
2019-10-17 15:04:50 +01:00
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
"github.com/shopspring/decimal"
|
2019-10-17 15:04:50 +01:00
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2021-06-22 01:09:56 +01:00
|
|
|
"github.com/stripe/stripe-go/v72"
|
2020-02-13 18:08:45 +00:00
|
|
|
"github.com/zeebo/errs"
|
2019-10-17 15:04:50 +01:00
|
|
|
|
2020-02-13 18:08:45 +00:00
|
|
|
"storj.io/common/errs2"
|
2019-12-27 11:48:47 +00:00
|
|
|
"storj.io/common/memory"
|
|
|
|
"storj.io/common/testcontext"
|
|
|
|
"storj.io/common/testrand"
|
2020-03-30 10:08:50 +01:00
|
|
|
"storj.io/common/uuid"
|
2020-07-17 16:17:21 +01:00
|
|
|
"storj.io/storj/private/testplanet"
|
2019-10-17 15:04:50 +01:00
|
|
|
"storj.io/storj/satellite"
|
|
|
|
"storj.io/storj/satellite/payments/coinpayments"
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
"storj.io/storj/satellite/payments/monetary"
|
2019-10-17 15:04:50 +01:00
|
|
|
"storj.io/storj/satellite/payments/stripecoinpayments"
|
|
|
|
"storj.io/storj/satellite/satellitedb/satellitedbtest"
|
|
|
|
)
|
|
|
|
|
2019-11-05 13:16:02 +00:00
|
|
|
func TestTransactionsDB(t *testing.T) {
|
2020-01-19 16:29:15 +00:00
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
2019-11-05 13:16:02 +00:00
|
|
|
transactions := db.StripeCoinPayments().Transactions()
|
2019-10-17 15:04:50 +01:00
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
amount, err := monetary.AmountFromString("2.0000000000000000005", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
received, err := monetary.AmountFromString("1.0000000000000000003", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
userID := testrand.UUID()
|
2019-10-23 13:04:54 +01:00
|
|
|
|
|
|
|
createTx := stripecoinpayments.Transaction{
|
|
|
|
ID: "testID",
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
AccountID: userID,
|
2019-10-23 13:04:54 +01:00
|
|
|
Address: "testAddress",
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Amount: amount,
|
|
|
|
Received: received,
|
2020-01-14 13:38:32 +00:00
|
|
|
Status: coinpayments.StatusPending,
|
2019-10-23 13:04:54 +01:00
|
|
|
Key: "testKey",
|
2019-11-15 14:59:39 +00:00
|
|
|
Timeout: time.Second * 60,
|
2019-10-23 13:04:54 +01:00
|
|
|
}
|
|
|
|
|
2019-10-17 15:04:50 +01:00
|
|
|
t.Run("insert", func(t *testing.T) {
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
createdAt, err := transactions.Insert(ctx, createTx)
|
2019-10-23 13:04:54 +01:00
|
|
|
require.NoError(t, err)
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
requireSaneTimestamp(t, createdAt)
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
txs, err := transactions.ListAccount(ctx, userID)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Len(t, txs, 1)
|
|
|
|
compareTransactions(t, createTx, txs[0])
|
2019-10-23 13:04:54 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("update", func(t *testing.T) {
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
received, err := monetary.AmountFromString("6.0000000000000000001", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
2019-10-17 15:04:50 +01:00
|
|
|
|
2019-10-23 13:04:54 +01:00
|
|
|
update := stripecoinpayments.TransactionUpdate{
|
|
|
|
TransactionID: createTx.ID,
|
2020-01-14 13:38:32 +00:00
|
|
|
Status: coinpayments.StatusReceived,
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Received: received,
|
2019-10-23 13:04:54 +01:00
|
|
|
}
|
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
err = transactions.Update(ctx, []stripecoinpayments.TransactionUpdate{update}, nil)
|
2019-10-23 13:04:54 +01:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
page, err := transactions.ListPending(ctx, 0, 1, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
require.Len(t, page.Transactions, 1)
|
2019-10-23 13:04:54 +01:00
|
|
|
assert.Equal(t, createTx.ID, page.Transactions[0].ID)
|
|
|
|
assert.Equal(t, update.Received, page.Transactions[0].Received)
|
|
|
|
assert.Equal(t, update.Status, page.Transactions[0].Status)
|
2019-10-29 16:04:34 +00:00
|
|
|
|
|
|
|
err = transactions.Update(ctx,
|
|
|
|
[]stripecoinpayments.TransactionUpdate{
|
|
|
|
{
|
|
|
|
TransactionID: createTx.ID,
|
2020-01-14 13:38:32 +00:00
|
|
|
Status: coinpayments.StatusCompleted,
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Received: received,
|
2019-10-29 16:04:34 +00:00
|
|
|
},
|
|
|
|
},
|
|
|
|
coinpayments.TransactionIDList{
|
|
|
|
createTx.ID,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
page, err = transactions.ListUnapplied(ctx, 0, 1, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotNil(t, page.Transactions)
|
|
|
|
require.Equal(t, 1, len(page.Transactions))
|
|
|
|
|
|
|
|
assert.Equal(t, createTx.ID, page.Transactions[0].ID)
|
|
|
|
assert.Equal(t, update.Received, page.Transactions[0].Received)
|
2020-01-14 13:38:32 +00:00
|
|
|
assert.Equal(t, coinpayments.StatusCompleted, page.Transactions[0].Status)
|
2019-10-29 16:04:34 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("consume", func(t *testing.T) {
|
|
|
|
err := transactions.Consume(ctx, createTx.ID)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
page, err := transactions.ListUnapplied(ctx, 0, 1, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
assert.Nil(t, page.Transactions)
|
|
|
|
assert.Equal(t, 0, len(page.Transactions))
|
2019-10-23 13:04:54 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
func requireSaneTimestamp(t *testing.T, when time.Time) {
|
|
|
|
// ensure time value is sane. I apologize to you people of the future when this starts breaking
|
|
|
|
require.Truef(t, when.After(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)),
|
|
|
|
"%s seems too small to be a valid creation timestamp", when)
|
|
|
|
require.Truef(t, when.Before(time.Date(2500, 1, 1, 0, 0, 0, 0, time.UTC)),
|
|
|
|
"%s seems too large to be a valid creation timestamp", when)
|
|
|
|
}
|
|
|
|
|
2020-02-13 18:08:45 +00:00
|
|
|
func TestConcurrentConsume(t *testing.T) {
|
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
|
|
|
transactions := db.StripeCoinPayments().Transactions()
|
|
|
|
|
|
|
|
const concurrentTries = 30
|
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
amount, err := monetary.AmountFromString("2.0000000000000000005", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
received, err := monetary.AmountFromString("1.0000000000000000003", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
userID := testrand.UUID()
|
|
|
|
txID := coinpayments.TransactionID("testID")
|
2020-02-13 18:08:45 +00:00
|
|
|
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
_, err = transactions.Insert(ctx,
|
2020-02-13 18:08:45 +00:00
|
|
|
stripecoinpayments.Transaction{
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
ID: txID,
|
|
|
|
AccountID: userID,
|
2020-02-13 18:08:45 +00:00
|
|
|
Address: "testAddress",
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Amount: amount,
|
|
|
|
Received: received,
|
2020-02-13 18:08:45 +00:00
|
|
|
Status: coinpayments.StatusPending,
|
|
|
|
Key: "testKey",
|
|
|
|
Timeout: time.Second * 60,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
err = transactions.Update(ctx,
|
|
|
|
[]stripecoinpayments.TransactionUpdate{{
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
TransactionID: txID,
|
2020-02-13 18:08:45 +00:00
|
|
|
Status: coinpayments.StatusCompleted,
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Received: received,
|
2020-02-13 18:08:45 +00:00
|
|
|
}},
|
|
|
|
coinpayments.TransactionIDList{
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
txID,
|
2020-02-13 18:08:45 +00:00
|
|
|
},
|
|
|
|
)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
var errLock sync.Mutex
|
|
|
|
var alreadyConsumed []error
|
|
|
|
|
|
|
|
appendError := func(err error) {
|
|
|
|
defer errLock.Unlock()
|
|
|
|
errLock.Lock()
|
|
|
|
|
|
|
|
alreadyConsumed = append(alreadyConsumed, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
var group errs2.Group
|
|
|
|
for i := 0; i < concurrentTries; i++ {
|
|
|
|
group.Go(func() error {
|
satellite/satellitedb: prepare to remove big.Float from db
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
Now that we have amounts represented using monetary.Amount, we can
simply store them in the database using integers (as given by the
.BaseUnits() method on monetary.Amount).
We should move toward storing the currency along with any monetary
amount, wherever we are storing amounts, because satellites might want
to deal with currencies other than STORJ and USD. Even better, it
becomes much clearer what currency each monetary value is _supposed_ to
be in (I had to dig through code to find that out for our current
monetary columns).
Deployment
----------
Getting rid of the big.Float columns will take multiple deployment
steps. There does not seem to be any way to make the change in a way
that lets existing queries continue to work on CockroachDB (it could be
done with rules and triggers and a stored procedure that knows how to
gob-decode big.Float objects, but CockroachDB doesn't have rules _or_
triggers _or_ stored procedures). Instead, in this first step, we make
no changes to the database schema, but add code that knows how to deal
with the planned changes to the schema when they are made in a future
"step 2" deployment. All functions that deal with the
coinbase_transactions table have been taught to recognize the "undefined
column" error, and when it is seen, to call a separate "transition shim"
function to accomplish the task. Once all the services are running this
code, and the step 2 deployment makes breaking changes to the schema,
any services that are still running and connected to the database will
keep working correctly because of the fallback code included here. The
step 2 deployment can be made without these transition shims included,
because it will apply the database schema changes before any of its code
runs.
Step 1:
No schema changes; just include code that recognizes the
"undefined column" error when dealing with the
coinbase_transactions or stripecoinpayments_tx_conversion_rates
tables, and if found, assumes that the column changes from Step
2 have already been made.
Step 2:
In coinbase_transactions:
* change the names of the 'amount' and 'received' columns to
'amount_gob' and 'received_gob' respectively
* add new 'amount_numeric' and 'received_numeric' columns with
INT8 type.
In stripecoinpayments_tx_conversion_rates:
* change the name of the 'rate' column to 'rate_gob'
* add new 'rate_numeric' column with NUMERIC(8, 8) type
Code reading from either of these tables must query both the X_gob
and X_numeric columns. If X_numeric is not null, its value should
be used; otherwise, the gob-encoded big.Float in X_gob should be
used. A chore might be included in this step that transitions values
from X_gob to X_numeric a few rows at a time.
Step 3:
Once all prod satellites have no values left in the _gob columns, we
can drop those columns and add NOT NULL constraints to the _numeric
columns.
Change-Id: Id6db304b404e6fde44f5a8c23cdaeeaaa2324f20
2021-08-10 23:30:23 +01:00
|
|
|
err := transactions.Consume(ctx, txID)
|
2020-02-13 18:08:45 +00:00
|
|
|
|
|
|
|
if err == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2020-07-14 14:04:38 +01:00
|
|
|
if errors.Is(err, stripecoinpayments.ErrTransactionConsumed) {
|
2020-02-13 18:08:45 +00:00
|
|
|
appendError(err)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
require.NoError(t, errs.Combine(group.Wait()...))
|
|
|
|
require.Equal(t, concurrentTries-1, len(alreadyConsumed))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-11-05 13:16:02 +00:00
|
|
|
func TestTransactionsDBList(t *testing.T) {
|
2019-10-29 16:04:34 +00:00
|
|
|
ctx := testcontext.New(t)
|
|
|
|
defer ctx.Cleanup()
|
|
|
|
|
|
|
|
const (
|
2020-02-11 13:11:14 +00:00
|
|
|
limit = 5
|
|
|
|
transactionCount = limit * 4
|
2019-10-29 16:04:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// create transactions
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
amount, err := monetary.AmountFromString("4.0000000000000000005", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
received, err := monetary.AmountFromString("5.0000000000000000003", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
2019-10-29 16:04:34 +00:00
|
|
|
|
|
|
|
var txs []stripecoinpayments.Transaction
|
|
|
|
for i := 0; i < transactionCount; i++ {
|
|
|
|
id := base64.StdEncoding.EncodeToString(testrand.Bytes(4 * memory.B))
|
|
|
|
addr := base64.StdEncoding.EncodeToString(testrand.Bytes(4 * memory.B))
|
|
|
|
key := base64.StdEncoding.EncodeToString(testrand.Bytes(4 * memory.B))
|
|
|
|
|
2020-01-14 13:38:32 +00:00
|
|
|
status := coinpayments.StatusPending
|
|
|
|
if i%2 == 0 {
|
|
|
|
status = coinpayments.StatusReceived
|
|
|
|
}
|
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
createTX := stripecoinpayments.Transaction{
|
|
|
|
ID: coinpayments.TransactionID(id),
|
|
|
|
AccountID: uuid.UUID{},
|
|
|
|
Address: addr,
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Amount: amount,
|
|
|
|
Received: received,
|
2020-01-14 13:38:32 +00:00
|
|
|
Status: status,
|
2019-10-29 16:04:34 +00:00
|
|
|
Key: key,
|
|
|
|
}
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
txs = append(txs, createTX)
|
|
|
|
}
|
2020-01-14 13:38:32 +00:00
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
t.Run("pending transactions", func(t *testing.T) {
|
2020-01-19 16:29:15 +00:00
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
2019-10-29 16:04:34 +00:00
|
|
|
for _, tx := range txs {
|
2019-11-05 13:16:02 +00:00
|
|
|
_, err := db.StripeCoinPayments().Transactions().Insert(ctx, tx)
|
2019-10-29 16:04:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
}
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2020-02-11 13:11:14 +00:00
|
|
|
page, err := db.StripeCoinPayments().Transactions().ListPending(ctx, 0, limit, time.Now())
|
2019-10-29 16:04:34 +00:00
|
|
|
require.NoError(t, err)
|
2020-02-11 13:11:14 +00:00
|
|
|
|
|
|
|
pendingTXs := page.Transactions
|
|
|
|
|
|
|
|
for page.Next {
|
|
|
|
page, err = db.StripeCoinPayments().Transactions().ListPending(ctx, page.NextOffset, limit, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
pendingTXs = append(pendingTXs, page.Transactions...)
|
|
|
|
}
|
|
|
|
|
2020-01-14 13:38:32 +00:00
|
|
|
require.False(t, page.Next)
|
2020-02-11 13:11:14 +00:00
|
|
|
require.Equal(t, transactionCount, len(pendingTXs))
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
for _, act := range page.Transactions {
|
|
|
|
for _, exp := range txs {
|
|
|
|
if act.ID == exp.ID {
|
|
|
|
compareTransactions(t, exp, act)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
t.Run("unapplied transaction", func(t *testing.T) {
|
2020-01-19 16:29:15 +00:00
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
2019-10-29 16:04:34 +00:00
|
|
|
var updatedTxs []stripecoinpayments.Transaction
|
|
|
|
var updates []stripecoinpayments.TransactionUpdate
|
|
|
|
var applies coinpayments.TransactionIDList
|
|
|
|
|
|
|
|
for _, tx := range txs {
|
2019-11-05 13:16:02 +00:00
|
|
|
_, err := db.StripeCoinPayments().Transactions().Insert(ctx, tx)
|
2019-10-29 16:04:34 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
2020-01-14 13:38:32 +00:00
|
|
|
tx.Status = coinpayments.StatusCompleted
|
2019-10-29 16:04:34 +00:00
|
|
|
|
|
|
|
updates = append(updates,
|
|
|
|
stripecoinpayments.TransactionUpdate{
|
|
|
|
TransactionID: tx.ID,
|
|
|
|
Status: tx.Status,
|
|
|
|
Received: tx.Received,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
|
|
|
|
applies = append(applies, tx.ID)
|
|
|
|
updatedTxs = append(updatedTxs, tx)
|
2019-10-17 15:04:50 +01:00
|
|
|
}
|
|
|
|
|
2019-11-05 13:16:02 +00:00
|
|
|
err := db.StripeCoinPayments().Transactions().Update(ctx, updates, applies)
|
2019-10-17 15:04:50 +01:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
2020-02-11 13:11:14 +00:00
|
|
|
page, err := db.StripeCoinPayments().Transactions().ListUnapplied(ctx, 0, limit, time.Now())
|
2019-10-29 16:04:34 +00:00
|
|
|
require.NoError(t, err)
|
2020-02-11 13:11:14 +00:00
|
|
|
|
|
|
|
unappliedTXs := page.Transactions
|
|
|
|
|
|
|
|
for page.Next {
|
|
|
|
page, err = db.StripeCoinPayments().Transactions().ListUnapplied(ctx, page.NextOffset, limit, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
unappliedTXs = append(unappliedTXs, page.Transactions...)
|
|
|
|
}
|
|
|
|
|
2020-01-14 13:38:32 +00:00
|
|
|
require.False(t, page.Next)
|
2020-02-11 13:11:14 +00:00
|
|
|
require.Equal(t, transactionCount, len(unappliedTXs))
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2019-10-29 16:04:34 +00:00
|
|
|
for _, act := range page.Transactions {
|
|
|
|
for _, exp := range updatedTxs {
|
|
|
|
if act.ID == exp.ID {
|
|
|
|
compareTransactions(t, exp, act)
|
|
|
|
}
|
2019-10-23 13:04:54 +01:00
|
|
|
}
|
|
|
|
}
|
2019-10-29 16:04:34 +00:00
|
|
|
})
|
2019-10-17 15:04:50 +01:00
|
|
|
})
|
|
|
|
}
|
2019-10-23 13:04:54 +01:00
|
|
|
|
2019-11-15 14:59:39 +00:00
|
|
|
func TestTransactionsDBRates(t *testing.T) {
|
2020-01-19 16:29:15 +00:00
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
2019-11-15 14:59:39 +00:00
|
|
|
transactions := db.StripeCoinPayments().Transactions()
|
|
|
|
|
2021-07-29 02:33:05 +01:00
|
|
|
val, err := decimal.NewFromString("4.000000000000005")
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
require.NoError(t, err)
|
2019-11-15 14:59:39 +00:00
|
|
|
|
|
|
|
const txID = "tx_id"
|
|
|
|
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
err = transactions.LockRate(ctx, txID, val)
|
2019-11-15 14:59:39 +00:00
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
rate, err := transactions.GetLockedRate(ctx, txID)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
assert.Equal(t, val, rate)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2019-10-23 13:04:54 +01:00
|
|
|
// compareTransactions is a helper method to compare tx used to create db entry,
|
|
|
|
// with the tx returned from the db. Method doesn't compare created at field, but
|
|
|
|
// ensures that is not empty.
|
|
|
|
func compareTransactions(t *testing.T, exp, act stripecoinpayments.Transaction) {
|
|
|
|
assert.Equal(t, exp.ID, act.ID)
|
|
|
|
assert.Equal(t, exp.AccountID, act.AccountID)
|
|
|
|
assert.Equal(t, exp.Address, act.Address)
|
|
|
|
assert.Equal(t, exp.Amount, act.Amount)
|
|
|
|
assert.Equal(t, exp.Received, act.Received)
|
|
|
|
assert.Equal(t, exp.Status, act.Status)
|
|
|
|
assert.Equal(t, exp.Key, act.Key)
|
2019-11-15 14:59:39 +00:00
|
|
|
assert.Equal(t, exp.Timeout, act.Timeout)
|
2019-10-23 13:04:54 +01:00
|
|
|
assert.False(t, act.CreatedAt.IsZero())
|
|
|
|
}
|
2020-07-17 16:17:21 +01:00
|
|
|
|
|
|
|
func TestTransactions_ApplyTransactionBalance(t *testing.T) {
|
|
|
|
testplanet.Run(t, testplanet.Config{
|
|
|
|
SatelliteCount: 1, StorageNodeCount: 0, UplinkCount: 1,
|
|
|
|
}, func(t *testing.T, ctx *testcontext.Context, planet *testplanet.Planet) {
|
|
|
|
satellite := planet.Satellites[0]
|
|
|
|
transactions := satellite.API.DB.StripeCoinPayments().Transactions()
|
|
|
|
userID := planet.Uplinks[0].Projects[0].Owner.ID
|
|
|
|
|
|
|
|
satellite.Core.Payments.Chore.TransactionCycle.Pause()
|
|
|
|
satellite.Core.Payments.Chore.AccountBalanceCycle.Pause()
|
|
|
|
|
|
|
|
// Emulate a deposit through CoinPayments.
|
|
|
|
txID := coinpayments.TransactionID("testID")
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
storjAmount, err := monetary.AmountFromString("100", monetary.StorjToken)
|
|
|
|
require.NoError(t, err)
|
|
|
|
storjUSDRate, err := decimal.NewFromString("0.2")
|
|
|
|
require.NoError(t, err)
|
2020-07-17 16:17:21 +01:00
|
|
|
|
|
|
|
createTx := stripecoinpayments.Transaction{
|
|
|
|
ID: txID,
|
|
|
|
AccountID: userID,
|
|
|
|
Address: "testAddress",
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Amount: storjAmount,
|
|
|
|
Received: storjAmount,
|
2020-07-17 16:17:21 +01:00
|
|
|
Status: coinpayments.StatusPending,
|
|
|
|
Key: "testKey",
|
|
|
|
Timeout: time.Second * 60,
|
|
|
|
}
|
|
|
|
|
|
|
|
tx, err := transactions.Insert(ctx, createTx)
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.NotNil(t, tx)
|
|
|
|
|
|
|
|
update := stripecoinpayments.TransactionUpdate{
|
|
|
|
TransactionID: createTx.ID,
|
|
|
|
Status: coinpayments.StatusReceived,
|
satellite/payments: specialized type for monetary amounts
Why: big.Float is not an ideal type for dealing with monetary amounts,
because no matter how high the precision, some non-integer decimal
values can not be represented exactly in base-2 floating point. Also,
storing gob-encoded big.Float values in the database makes it very hard
to use those values in meaningful queries, making it difficult to do
any sort of analysis on billing.
For better accuracy, then, we can just represent monetary values as
integers (in whatever base units are appropriate for the currency). For
example, STORJ tokens or Bitcoins can not be split into pieces smaller
than 10^-8, so we can store amounts of STORJ or BTC with precision
simply by moving the decimal point 8 digits to the right. For USD values
(assuming we don't want to deal with fractional cents), we can move the
decimal point 2 digits to the right.
To make it easier and less error-prone to deal with the math involved, I
introduce here a new type, monetary.Amount, instances of which have an
associated value _and_ a currency.
Change-Id: I03395d52f0e2473cf301361f6033722b54640265
2021-08-10 23:29:50 +01:00
|
|
|
Received: storjAmount,
|
2020-07-17 16:17:21 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
err = transactions.Update(ctx, []stripecoinpayments.TransactionUpdate{update}, coinpayments.TransactionIDList{createTx.ID})
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
// Check that the CoinPayments transaction is waiting to be applied to the Stripe customer balance.
|
|
|
|
page, err := transactions.ListUnapplied(ctx, 0, 1, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
require.Len(t, page.Transactions, 1)
|
|
|
|
|
|
|
|
err = transactions.LockRate(ctx, txID, storjUSDRate)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
// Trigger the AccountBalanceCycle. This calls Service.applyTransactionBalance()
|
|
|
|
satellite.Core.Payments.Chore.AccountBalanceCycle.TriggerWait()
|
|
|
|
|
|
|
|
cusID, err := satellite.API.DB.StripeCoinPayments().Customers().GetCustomerID(ctx, userID)
|
|
|
|
require.NoError(t, err)
|
|
|
|
|
|
|
|
// Check that the CoinPayments deposit is reflected in the Stripe customer balance.
|
|
|
|
it := satellite.API.Payments.Stripe.CustomerBalanceTransactions().List(&stripe.CustomerBalanceTransactionListParams{Customer: stripe.String(cusID)})
|
|
|
|
require.NoError(t, it.Err())
|
|
|
|
require.True(t, it.Next())
|
|
|
|
cbt := it.CustomerBalanceTransaction()
|
|
|
|
require.EqualValues(t, -2000, cbt.Amount)
|
|
|
|
require.EqualValues(t, txID, cbt.Metadata["txID"])
|
|
|
|
require.EqualValues(t, "100", cbt.Metadata["storj_amount"])
|
|
|
|
require.EqualValues(t, "0.2", cbt.Metadata["storj_usd_rate"])
|
|
|
|
})
|
|
|
|
}
|
satellite/payments: chore to migrate big.Float values out of db
All code on known satellites at this moment in time should know how to
populate and use the new numeric columns on the
stripecoinpayments_tx_conversion_rates and coinpayments_transactions
tables in the satellite db. However, there are still gob-encoded
big.Float values in the database from before these columns existed. To
get rid of those values, so that we can excise the gob-decoding code
from the relevant sections, however, we need something to read the gob
bytestrings and convert them to numeric values, a few at a time, until
they're all gone.
To accomplish that, this change adds two chores to be run in the
satellite core process- one for the coinpayments_transactions table, and
one for the stripecoinpayments_tx_conversion_rates table. They should
run relatively infrequently, so that we do not impose any undue load on
processing resources or the db.
Both of these chores work without using explicit sql transactions, but
should still be concurrent-safe, since they work by way of
compare-and-swap type operations.
If the satellite core process needs to be restarted, both of these
chores will start scanning for migrateable rows from the beginning of
the id space again. This is not ideal, but shouldn't be a problem (as
far as I can tell, there are only a few thousand rows at most in either
of these tables on any production satellite).
Change-Id: I733b7cd96760d506a1cf52735f598c6c3aa19735
2021-10-29 14:32:59 +01:00
|
|
|
|
|
|
|
func TestDatabaseGobEncodedBigFloatTransactionMigration(t *testing.T) {
|
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
|
|
|
transactions := db.StripeCoinPayments().Transactions()
|
|
|
|
|
|
|
|
testTransactions, ok := transactions.(interface {
|
|
|
|
ForTestingOnlyInsertGobTransaction(ctx context.Context, tx stripecoinpayments.Transaction) (time.Time, error)
|
|
|
|
})
|
|
|
|
require.Truef(t, ok, "transactions object of type %T does not have the needed test hook method", transactions)
|
|
|
|
|
|
|
|
// make some random records, insert in db
|
|
|
|
const numRecords = 100
|
|
|
|
asInserted := make([]stripecoinpayments.Transaction, 0, numRecords)
|
|
|
|
for x := 0; x < numRecords; x++ {
|
|
|
|
tx := stripecoinpayments.Transaction{
|
|
|
|
ID: coinpayments.TransactionID(fmt.Sprintf("transaction%05d", x)),
|
|
|
|
Status: coinpayments.Status(x % 2), // 0 (pending) or 1 (received)
|
|
|
|
AccountID: testrand.UUID(),
|
|
|
|
Amount: monetary.AmountFromBaseUnits(testrand.Int63n(1e15), monetary.StorjToken),
|
|
|
|
Received: monetary.AmountFromBaseUnits(testrand.Int63n(1e15), monetary.StorjToken),
|
|
|
|
Address: fmt.Sprintf("%x", testrand.Bytes(20)),
|
|
|
|
Key: fmt.Sprintf("%x", testrand.Bytes(20)),
|
|
|
|
}
|
|
|
|
createTime, err := testTransactions.ForTestingOnlyInsertGobTransaction(ctx, tx)
|
|
|
|
require.NoError(t, err)
|
|
|
|
tx.CreatedAt = createTime
|
|
|
|
asInserted = append(asInserted, tx)
|
|
|
|
}
|
|
|
|
|
|
|
|
// run migration in a number of batches
|
|
|
|
const (
|
|
|
|
numBatches = 6
|
|
|
|
batchSize = (numRecords + numBatches - 1) / numBatches
|
|
|
|
)
|
|
|
|
var (
|
|
|
|
totalMigrated int
|
|
|
|
batchesSoFar int
|
|
|
|
rangeStart string
|
|
|
|
)
|
|
|
|
|
|
|
|
// check that batches work as expected
|
|
|
|
for {
|
|
|
|
migrated, nextRangeStart, err := transactions.MigrateGobFloatTransactionRecords(ctx, rangeStart, batchSize)
|
|
|
|
require.NoError(t, err)
|
|
|
|
batchesSoFar++
|
|
|
|
totalMigrated += migrated
|
|
|
|
|
|
|
|
// no interference from other db clients, so all should succeed
|
|
|
|
if migrated < batchSize {
|
|
|
|
// we expect this to be the last batch, so nextRangeStart should be the empty string
|
|
|
|
assert.Equal(t, "", nextRangeStart)
|
|
|
|
assert.Equal(t, numRecords, totalMigrated)
|
|
|
|
if migrated == 0 {
|
|
|
|
// it took an extra batch to find out we were done, because batchSize % numRecords == 0
|
|
|
|
assert.Equal(t, numBatches+1, batchesSoFar)
|
|
|
|
} else {
|
|
|
|
assert.Equal(t, numBatches, batchesSoFar)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
assert.NotNil(t, nextRangeStart)
|
|
|
|
assert.Equal(t, batchSize, migrated)
|
|
|
|
assert.LessOrEqual(t, totalMigrated, numRecords)
|
|
|
|
|
|
|
|
require.Less(t, rangeStart, nextRangeStart)
|
|
|
|
rangeStart = nextRangeStart
|
|
|
|
}
|
|
|
|
|
|
|
|
// read results back in and ensure values are still as expected
|
|
|
|
transactionsPage, err := transactions.ListPending(ctx, 0, numRecords+1, time.Now())
|
|
|
|
require.NoError(t, err)
|
|
|
|
assert.Len(t, transactionsPage.Transactions, numRecords)
|
|
|
|
assert.False(t, transactionsPage.Next)
|
|
|
|
|
|
|
|
// sort the output values to make comparison simple (they're
|
|
|
|
// currently sorted by created_at, which might be the same
|
|
|
|
// ordering we want, but it's not guaranteed, as pg and crdb
|
|
|
|
// only have time values to microsecond resolution).
|
|
|
|
sort.Slice(transactionsPage.Transactions, func(i, j int) bool {
|
|
|
|
return transactionsPage.Transactions[i].ID < transactionsPage.Transactions[j].ID
|
|
|
|
})
|
|
|
|
|
|
|
|
assert.Equal(t, asInserted, transactionsPage.Transactions)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestDatabaseGobEncodedBigFloatConversionRateMigration(t *testing.T) {
|
|
|
|
satellitedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db satellite.DB) {
|
|
|
|
transactions := db.StripeCoinPayments().Transactions()
|
|
|
|
|
|
|
|
testTransactions, ok := transactions.(interface {
|
|
|
|
ForTestingOnlyInsertGobConversionRate(ctx context.Context, txID coinpayments.TransactionID, rate decimal.Decimal) error
|
|
|
|
})
|
|
|
|
require.Truef(t, ok, "transactions object of type %T does not have the needed test hook method", transactions)
|
|
|
|
|
|
|
|
// make some random records, insert in db
|
|
|
|
const numRecords = 100
|
|
|
|
|
|
|
|
type rateRecord struct {
|
|
|
|
txID coinpayments.TransactionID
|
|
|
|
rate decimal.Decimal
|
|
|
|
}
|
|
|
|
asInserted := make([]rateRecord, 0, numRecords)
|
|
|
|
for x := 0; x < numRecords; x++ {
|
|
|
|
rateDecimal := mustRandomDecimalNumber(4, 11)
|
|
|
|
rr := rateRecord{
|
|
|
|
txID: coinpayments.TransactionID(fmt.Sprintf("transaction%05d", x)),
|
|
|
|
rate: rateDecimal,
|
|
|
|
}
|
|
|
|
err := testTransactions.ForTestingOnlyInsertGobConversionRate(ctx, rr.txID, rr.rate)
|
|
|
|
require.NoError(t, err)
|
|
|
|
asInserted = append(asInserted, rr)
|
|
|
|
}
|
|
|
|
|
|
|
|
// run migration in a number of batches
|
|
|
|
const (
|
|
|
|
numBatches = 6
|
|
|
|
batchSize = (numRecords + numBatches - 1) / numBatches
|
|
|
|
)
|
|
|
|
var (
|
|
|
|
totalMigrated int
|
|
|
|
batchesSoFar int
|
|
|
|
rangeStart string
|
|
|
|
)
|
|
|
|
|
|
|
|
// check that batches work as expected
|
|
|
|
for {
|
|
|
|
migrated, nextRangeStart, err := transactions.MigrateGobFloatConversionRateRecords(ctx, rangeStart, batchSize)
|
|
|
|
require.NoError(t, err)
|
|
|
|
batchesSoFar++
|
|
|
|
totalMigrated += migrated
|
|
|
|
|
|
|
|
// no interference from other db clients, so all should succeed
|
|
|
|
if migrated < batchSize {
|
|
|
|
// we expect this to be the last batch, so nextRangeStart should be the empty string
|
|
|
|
assert.Equal(t, "", nextRangeStart)
|
|
|
|
assert.Equal(t, numRecords, totalMigrated)
|
|
|
|
if migrated == 0 {
|
|
|
|
// it took an extra batch to find out we were done, because batchSize % numRecords == 0
|
|
|
|
assert.Equal(t, numBatches+1, batchesSoFar)
|
|
|
|
} else {
|
|
|
|
assert.Equal(t, numBatches, batchesSoFar)
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
assert.NotNil(t, nextRangeStart)
|
|
|
|
assert.Equal(t, batchSize, migrated)
|
|
|
|
assert.LessOrEqual(t, totalMigrated, numRecords)
|
|
|
|
|
|
|
|
require.Less(t, rangeStart, nextRangeStart)
|
|
|
|
rangeStart = nextRangeStart
|
|
|
|
}
|
|
|
|
|
|
|
|
// read results back in and ensure values are still as expected
|
|
|
|
for n := 0; n < numRecords; n++ {
|
|
|
|
rate, err := transactions.GetLockedRate(ctx, asInserted[n].txID)
|
|
|
|
require.NoError(t, err)
|
|
|
|
assert.Truef(t, asInserted[n].rate.Equal(rate), "for row %d: expected=%s, got=%s", n, asInserted[n].rate.String(), rate.String())
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustRandomDecimalNumber(wholePartDigits, fractionalPartDigits int) decimal.Decimal {
|
|
|
|
decimalNumber, err := randomDecimalNumber(wholePartDigits, fractionalPartDigits)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return decimalNumber
|
|
|
|
}
|
|
|
|
|
|
|
|
func randomDecimalNumber(wholePartDigits, fractionalPartDigits int) (decimal.Decimal, error) {
|
|
|
|
wholePart := randomNumberWithNDigits(wholePartDigits)
|
|
|
|
fractionalPart := randomNumberWithNDigits(fractionalPartDigits)
|
|
|
|
numberAsString := fmt.Sprintf("%d.%0*d", wholePart, fractionalPartDigits, fractionalPart)
|
|
|
|
return decimal.NewFromString(numberAsString)
|
|
|
|
}
|
|
|
|
|
|
|
|
func randomNumberWithNDigits(numDigits int) *big.Int {
|
|
|
|
randomSource := rand.New(rand.NewSource(rand.Int63()))
|
|
|
|
num := big.NewInt(10)
|
|
|
|
num.Exp(num, big.NewInt(int64(numDigits)), nil)
|
|
|
|
return num.Rand(randomSource, num)
|
|
|
|
}
|