-
Notifications
You must be signed in to change notification settings - Fork 49
/
validation.go
237 lines (205 loc) · 8.55 KB
/
validation.go
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package escrow
import (
"bytes"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/singnet/snet-daemon/authutils"
"github.com/singnet/snet-daemon/blockchain"
"github.com/singnet/snet-daemon/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"math/big"
)
const (
PrefixInSignature = "__MPE_claim_message"
//Agreed constant value
FreeCallPrefixSignature = "__prefix_free_trial"
//Agreed constant value
AllowedUserPrefixSignature = "__authorized_user"
)
type FreeCallPaymentValidator struct {
currentBlock func() (currentBlock *big.Int, err error)
freeCallSigner common.Address
}
func NewFreeCallPaymentValidator(funcCurrentBlock func() (currentBlock *big.Int, err error), signer common.Address) *FreeCallPaymentValidator {
return &FreeCallPaymentValidator{
currentBlock: funcCurrentBlock,
freeCallSigner: signer,
}
}
type AllowedUserPaymentValidator struct {
}
func (validator *AllowedUserPaymentValidator) Validate(payment *Payment) (err error) {
_, err = getSignerAddressFromPayment(payment)
return err
}
func (validator *FreeCallPaymentValidator) Validate(payment *FreeCallPayment) (err error) {
newSignature := true //this will be removed once dapp makes the changes to move to new Signature
signerAddress, err := validator.getSignerOfAuthTokenForFreeCall(payment)
if err != nil || *signerAddress != validator.freeCallSigner {
//Make sure the current Dapp is backward compatible , this will be removed once Dapp
//Makes the latest signature change with Token for Free calls
if signerAddress, err = validator.getSignerAddressForFreeCall(payment); err != nil {
return NewPaymentError(Unauthenticated, "payment signature is not valid")
}
newSignature = false
}
if *signerAddress != validator.freeCallSigner {
return NewPaymentError(Unauthenticated, "payment signer is not valid %v , %v", signerAddress.Hex(), validator.freeCallSigner.Hex())
}
if newSignature {
if err := authutils.CheckIfTokenHasExpired(payment.AuthTokenExpiryBlockNumber); err != nil {
return err
}
}
//Check for the current block Number
if err := validator.compareWithLatestBlockNumber(payment.CurrentBlockNumber); err != nil {
return err
}
return nil
}
// ChannelPaymentValidator validates payment using payment channel state.
type ChannelPaymentValidator struct {
currentBlock func() (currentBlock *big.Int, err error)
paymentExpirationThreshold func() (threshold *big.Int)
}
// NewChannelPaymentValidator returns new payment validator instance
func NewChannelPaymentValidator(processor *blockchain.Processor, cfg *viper.Viper, metadata *blockchain.OrganizationMetaData) *ChannelPaymentValidator {
return &ChannelPaymentValidator{
currentBlock: processor.CurrentBlock,
paymentExpirationThreshold: func() *big.Int {
return metadata.GetPaymentExpirationThreshold()
},
}
}
// Validate returns instance of PaymentError as error if validation fails, nil
// otherwise.
func (validator *ChannelPaymentValidator) Validate(payment *Payment, channel *PaymentChannelData) (err error) {
var log = log.WithField("payment", payment).WithField("channel", channel)
if payment.ChannelNonce.Cmp(channel.Nonce) != 0 {
log.Warn("Incorrect nonce is sent by client")
return NewPaymentError(IncorrectNonce, "incorrect payment channel nonce, latest: %v, sent: %v", channel.Nonce, payment.ChannelNonce)
}
signerAddress, err := getSignerAddressFromPayment(payment)
if err != nil {
return NewPaymentError(Unauthenticated, "payment signature is not valid")
}
log = log.WithField("signerAddress", blockchain.AddressToHex(signerAddress))
if *signerAddress != channel.Signer && *signerAddress != channel.Sender {
log.WithField("signerAddress", blockchain.AddressToHex(signerAddress)).Warn("Channel signer is not equal to payment signer/sender")
return NewPaymentError(Unauthenticated, "payment is not signed by channel signer/sender")
}
currentBlock, e := validator.currentBlock()
if e != nil {
return NewPaymentError(Internal, "cannot determine current block")
}
expirationThreshold := validator.paymentExpirationThreshold()
currentBlockWithThreshold := new(big.Int).Add(currentBlock, expirationThreshold)
if currentBlockWithThreshold.Cmp(channel.Expiration) >= 0 {
log.WithField("currentBlock", currentBlock).WithField("expirationThreshold", expirationThreshold).Warn("Channel expiration time is after expiration threshold")
return NewPaymentError(Unauthenticated, "payment channel is near to be expired, expiration time: %v, current block: %v, expiration threshold: %v", channel.Expiration, currentBlock, expirationThreshold)
}
if channel.FullAmount.Cmp(payment.Amount) < 0 {
log.Warn("Not enough tokens on payment channel")
return NewPaymentError(Unauthenticated, "not enough tokens on payment channel, channel amount: %v, payment amount: %v", channel.FullAmount, payment.Amount)
}
return
}
//Check if the block number passed is not more +- 5 from the latest block number on chain
func (validator *FreeCallPaymentValidator) compareWithLatestBlockNumber(blockNumberPassed *big.Int) error {
latestBlockNumber, err := validator.currentBlock()
if err != nil {
return err
}
differenceInBlockNumber := blockNumberPassed.Sub(blockNumberPassed, latestBlockNumber)
if differenceInBlockNumber.Abs(differenceInBlockNumber).Uint64() > authutils.AllowedBlockChainDifference {
return fmt.Errorf("authentication failed as the signature passed has expired")
}
return nil
}
func (validator *FreeCallPaymentValidator) getSignerAddressForFreeCall(payment *FreeCallPayment) (signer *common.Address, err error) {
println("block number:" + payment.CurrentBlockNumber.String())
message := bytes.Join([][]byte{
[]byte(FreeCallPrefixSignature),
[]byte(payment.UserId),
[]byte(config.GetString(config.OrganizationId)),
[]byte(config.GetString(config.ServiceId)),
bigIntToBytes(payment.CurrentBlockNumber),
}, nil)
signer, err = authutils.GetSignerAddressFromMessage(message, payment.Signature)
if err != nil {
log.WithField("payment", payment).WithError(err).Error("Cannot get signer from payment")
return nil, err
}
return signer, err
}
func getSignerAddressFromPayment(payment *Payment) (signer *common.Address, err error) {
message := bytes.Join([][]byte{
[]byte(PrefixInSignature),
payment.MpeContractAddress.Bytes(),
bigIntToBytes(payment.ChannelID),
bigIntToBytes(payment.ChannelNonce),
bigIntToBytes(payment.Amount),
}, nil)
signer, err = authutils.GetSignerAddressFromMessage(message, payment.Signature)
if err != nil {
log.WithField("payment", payment).WithError(err).Error("Cannot get signer from payment")
return nil, err
}
if err = checkCurationValidations(signer); err != nil {
log.Error(err)
return nil, err
}
return signer, err
}
func (validator *FreeCallPaymentValidator) getSignerOfAuthTokenForFreeCall(payment *FreeCallPayment) (signer *common.Address, err error) {
//signer-token = (user@mail, user-public-key, token_issue_date), this is generated by Market place Dapp
signer, err = getUserAddressFromSignatureOfFreeCalls(payment)
if err != nil {
return nil, err
}
message := bytes.Join([][]byte{
[]byte(payment.UserId),
signer.Bytes(),
bigIntToBytes(payment.AuthTokenExpiryBlockNumber),
}, nil)
return authutils.GetSignerAddressFromMessage(message, payment.AuthToken)
}
//user signs using his private key , the public adress of this user should be in the token issued by Dapp
func getUserAddressFromSignatureOfFreeCalls(payment *FreeCallPayment) (signer *common.Address, err error) {
message := bytes.Join([][]byte{
[]byte(FreeCallPrefixSignature),
[]byte(payment.UserId),
[]byte(config.GetString(config.OrganizationId)),
[]byte(config.GetString(config.ServiceId)),
[]byte(payment.GroupId),
bigIntToBytes(payment.CurrentBlockNumber),
(payment.AuthToken),
}, nil)
signer, err = authutils.GetSignerAddressFromMessage(message, payment.Signature)
if err != nil {
log.WithField("payment", payment).WithError(err).Error("Cannot get signer from payment")
return nil, err
}
if err = checkCurationValidations(signer); err != nil {
log.Error(err)
return nil, err
}
return signer, err
}
func bigIntToBytes(value *big.Int) []byte {
return common.BigToHash(value).Bytes()
}
func bytesToBigInt(bytes []byte) *big.Int {
return (&big.Int{}).SetBytes(bytes)
}
func checkCurationValidations(signer *common.Address) error {
//This is only to protect the Service provider in test environment from being
//hit by unknown users during curation process
if config.GetBool(config.AllowedUserFlag) {
if !config.IsAllowedUser(signer) {
return fmt.Errorf("you are not Authorized to call this service during curation process")
}
}
return nil
}