-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcommon.go
More file actions
212 lines (192 loc) · 7.95 KB
/
common.go
File metadata and controls
212 lines (192 loc) · 7.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package usecases
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/rsksmart/liquidity-provider-server/internal/entities"
"github.com/rsksmart/liquidity-provider-server/internal/entities/blockchain"
"github.com/rsksmart/liquidity-provider-server/internal/entities/liquidity_provider"
"math/big"
)
// used for error logging
type UseCaseId string
const (
GetPeginQuoteId UseCaseId = "GetPeginQuote"
GetPegoutQuoteId UseCaseId = "GetPegoutQuote"
AcceptPeginQuoteId UseCaseId = "AcceptPeginQuote"
AcceptPegoutQuoteId UseCaseId = "AcceptPegoutQuote"
ProviderDetailId UseCaseId = "ProviderDetail"
GetProvidersId UseCaseId = "GetProviders"
GetUserQuotesId UseCaseId = "GetUserQuotes"
ProviderResignId UseCaseId = "ProviderResign"
ChangeProviderStatusId UseCaseId = "ChangeProviderStatus"
GetCollateralId UseCaseId = "GetCollateral"
GetPegoutCollateralId UseCaseId = "GetPegoutCollateral"
AddCollateralId UseCaseId = "AddCollateral"
AddPegoutCollateralId UseCaseId = "AddPegoutCollateral"
WithdrawCollateralId UseCaseId = "WithdrawCollateral"
WithdrawPegoutCollateralId UseCaseId = "WithdrawPegoutCollateral"
CallForUserId UseCaseId = "CallForUser"
RegisterPeginId UseCaseId = "RegisterPegin"
SendPegoutId UseCaseId = "SendPegout"
RefundPegoutId UseCaseId = "RefundPegout"
ProviderRegistrationId UseCaseId = "ProviderRegistration"
GetWatchedPeginQuoteId UseCaseId = "GetWatchedPeginQuote"
GetWatchedPegoutQuoteId UseCaseId = "GetWatchedPegoutQuote"
ExpiredPeginQuoteId UseCaseId = "ExpiredPeginQuote"
ExpiredPegoutQuoteId UseCaseId = "ExpiredPegoutQuote"
UpdatePegoutDepositId UseCaseId = "UpdatePegoutDeposit"
InitPegoutDepositCacheId UseCaseId = "InitPegoutDepositCache"
CheckLiquidityId UseCaseId = "CheckLiquidity"
PenalizationId UseCaseId = "Penalization"
SetPeginConfigId UseCaseId = "SetPeginConfigUseCase"
SetPegoutConfigId UseCaseId = "SetPegoutConfigUseCase"
SetGeneralConfigId UseCaseId = "SetGeneralConfigUseCase"
LoginId UseCaseId = "Login"
ChangeCredentialsId UseCaseId = "ChangeCredentials"
DefaultCredentialsId UseCaseId = "GenerateDefaultCredentials"
GetManagementUiId UseCaseId = "GetManagementUi"
BridgePegoutId UseCaseId = "BridgePegout"
PeginQuoteStatusId UseCaseId = "PeginQuoteStatus"
PegoutQuoteStatusId UseCaseId = "PegoutQuoteStatus"
GetAvailableLiquidityId UseCaseId = "GetAvailableLiquidity"
UpdatePeginDepositId UseCaseId = "UpdatePeginDeposit"
ServerInfoId UseCaseId = "ServerInfo"
GetPeginReportId UseCaseId = "GetPeginReport"
GetPegoutReportId UseCaseId = "GetPegoutReport"
)
var (
NonRecoverableError = errors.New("non recoverable")
TxBelowMinimumError = errors.New("requested amount below bridge's min transaction value")
RskAddressNotSupportedError = errors.New("rsk address not supported")
QuoteNotFoundError = errors.New("quote not found")
QuoteNotAcceptedError = errors.New("quote not accepted")
ExpiredQuoteError = errors.New("expired quote")
NoLiquidityError = errors.New("not enough liquidity")
ProviderConfigurationError = errors.New("pegin and pegout providers are not using the same account")
WrongStateError = errors.New("quote with wrong state")
NoEnoughConfirmationsError = errors.New("not enough confirmations for transaction")
InsufficientAmountError = errors.New("insufficient amount")
AlreadyRegisteredError = errors.New("liquidity provider already registered")
ProviderNotResignedError = errors.New("provided hasn't completed resignation process")
IllegalQuoteStateError = errors.New("illegal quote state")
)
type ErrorArgs map[string]string
func NewErrorArgs() ErrorArgs {
return make(ErrorArgs)
}
func ErrorArg(key, value string) ErrorArgs {
return ErrorArgs{key: value}
}
func (args ErrorArgs) String() string {
if jsonString, err := json.Marshal(args); err != nil {
return ""
} else {
return string(jsonString)
}
}
func WrapUseCaseError(useCase UseCaseId, err error) error {
return WrapUseCaseErrorArgs(useCase, err, make(ErrorArgs, 0))
}
func WrapUseCaseErrorArgs(useCase UseCaseId, err error, args ErrorArgs) error {
if len(args) == 0 {
return fmt.Errorf("%s: %w", useCase, err)
} else {
return fmt.Errorf("%s: %w. Args: %v", useCase, err, args)
}
}
type DaoAmounts struct {
DaoGasAmount *entities.Wei
DaoFeeAmount *entities.Wei
}
func CalculateDaoAmounts(ctx context.Context, rsk blockchain.RootstockRpcServer, value *entities.Wei, daoFeePercentage uint64, feeCollectorAddress string) (DaoAmounts, error) {
var daoGasAmount *entities.Wei
daoFeeAmount := new(entities.Wei)
var err error
if daoFeePercentage == 0 {
return DaoAmounts{
DaoFeeAmount: entities.NewWei(0),
DaoGasAmount: entities.NewWei(0),
}, nil
}
daoFeeAmount.Mul(value, entities.NewUWei(daoFeePercentage))
daoFeeAmount.AsBigInt().Div(daoFeeAmount.AsBigInt(), big.NewInt(100))
daoGasAmount, err = rsk.EstimateGas(ctx, feeCollectorAddress, daoFeeAmount, make([]byte, 0))
if err != nil {
return DaoAmounts{}, err
}
return DaoAmounts{
DaoFeeAmount: daoFeeAmount,
DaoGasAmount: daoGasAmount,
}, nil
}
func ValidateMinLockValue(useCase UseCaseId, bridge blockchain.RootstockBridge, value *entities.Wei) error {
var err error
var minLockTxValue *entities.Wei
errorArgs := NewErrorArgs()
if minLockTxValue, err = bridge.GetMinimumLockTxValue(); err != nil {
return WrapUseCaseError(useCase, err)
}
if value.Cmp(minLockTxValue) < 0 {
errorArgs["minimum"] = minLockTxValue.String()
errorArgs["value"] = value.String()
return WrapUseCaseErrorArgs(useCase, TxBelowMinimumError, errorArgs)
}
return nil
}
func SignConfiguration[C liquidity_provider.ConfigurationType](
useCaseId UseCaseId,
signer entities.Signer,
hashFunction entities.HashFunction,
config C,
) (entities.Signed[C], error) {
configBytes, err := json.Marshal(config)
if err != nil {
return entities.Signed[C]{}, WrapUseCaseError(useCaseId, err)
}
hash := hashFunction(configBytes)
signature, err := signer.SignBytes(hash)
if err != nil {
return entities.Signed[C]{}, WrapUseCaseError(useCaseId, err)
}
signedConfig := entities.Signed[C]{
Value: config,
Hash: hex.EncodeToString(hash),
Signature: hex.EncodeToString(signature),
}
return signedConfig, nil
}
// RegisterCoinbaseTransaction registers the information of the coinbase transaction of the block of a specific transaction in the Rootstock Bridge.
// IMPORTANT: this function should not be called right now for security reasons. It is in the codebase for future compatibility but should not be used for now.
func RegisterCoinbaseTransaction(btcRpc blockchain.BitcoinNetwork, bridgeContract blockchain.RootstockBridge, tx blockchain.BitcoinTransactionInformation) error {
if !tx.HasWitness {
return nil
}
coinbaseInfo, err := btcRpc.GetCoinbaseInformation(tx.Hash)
if err != nil {
return err
}
_, err = bridgeContract.RegisterBtcCoinbaseTransaction(coinbaseInfo)
return err
}
// ValidateBridgeUtxoMin checks that all the UTXOs to an address of a Bitcoin transaction are above the Rootstock Bridge minimum
func ValidateBridgeUtxoMin(bridge blockchain.RootstockBridge, transaction blockchain.BitcoinTransactionInformation, address string) error {
minLockTxValueInWei, err := bridge.GetMinimumLockTxValue()
if err != nil {
return err
}
utxos := transaction.UTXOsToAddress(address)
if len(utxos) == 0 {
err = fmt.Errorf("no UTXO directed to address %s present in transaction", address)
return errors.Join(TxBelowMinimumError, err)
}
for _, utxo := range utxos {
if minLockTxValueInWei.Cmp(utxo) > 0 {
err = errors.New("not all the UTXOs are above the min lock value")
return errors.Join(TxBelowMinimumError, err)
}
}
return nil
}