github.com/n1ghtfa1l/go-vnt@v0.6.4-alpha.6/signer/core/api.go (about) 1 // Copyright 2018 The go-ethereum Authors 2 // This file is part of go-ethereum. 3 // 4 // go-ethereum is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // go-ethereum is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>. 16 17 package core 18 19 import ( 20 "context" 21 "encoding/json" 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "math/big" 26 "reflect" 27 28 "github.com/vntchain/go-vnt/accounts" 29 "github.com/vntchain/go-vnt/accounts/keystore" 30 "github.com/vntchain/go-vnt/common" 31 "github.com/vntchain/go-vnt/common/hexutil" 32 "github.com/vntchain/go-vnt/crypto" 33 "github.com/vntchain/go-vnt/internal/vntapi" 34 "github.com/vntchain/go-vnt/log" 35 "github.com/vntchain/go-vnt/rlp" 36 ) 37 38 // ExternalAPI defines the external API through which signing requests are made. 39 type ExternalAPI interface { 40 // List available accounts 41 List(ctx context.Context) (Accounts, error) 42 // New request to create a new account 43 New(ctx context.Context) (accounts.Account, error) 44 // SignTransaction request to sign the specified transaction 45 SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*vntapi.SignTransactionResult, error) 46 // Sign - request to sign the given data (plus prefix) 47 Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) 48 // EcRecover - request to perform ecrecover 49 EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) 50 // Export - request to export an account 51 Export(ctx context.Context, addr common.Address) (json.RawMessage, error) 52 // Import - request to import an account 53 Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) 54 } 55 56 // SignerUI specifies what method a UI needs to implement to be able to be used as a UI for the signer 57 type SignerUI interface { 58 // ApproveTx prompt the user for confirmation to request to sign Transaction 59 ApproveTx(request *SignTxRequest) (SignTxResponse, error) 60 // ApproveSignData prompt the user for confirmation to request to sign data 61 ApproveSignData(request *SignDataRequest) (SignDataResponse, error) 62 // ApproveExport prompt the user for confirmation to export encrypted Account json 63 ApproveExport(request *ExportRequest) (ExportResponse, error) 64 // ApproveImport prompt the user for confirmation to import Account json 65 ApproveImport(request *ImportRequest) (ImportResponse, error) 66 // ApproveListing prompt the user for confirmation to list accounts 67 // the list of accounts to list can be modified by the UI 68 ApproveListing(request *ListRequest) (ListResponse, error) 69 // ApproveNewAccount prompt the user for confirmation to create new Account, and reveal to caller 70 ApproveNewAccount(request *NewAccountRequest) (NewAccountResponse, error) 71 // ShowError displays error message to user 72 ShowError(message string) 73 // ShowInfo displays info message to user 74 ShowInfo(message string) 75 // OnApprovedTx notifies the UI about a transaction having been successfully signed. 76 // This method can be used by a UI to keep track of e.g. how much has been sent to a particular recipient. 77 OnApprovedTx(tx vntapi.SignTransactionResult) 78 // OnSignerStartup is invoked when the signer boots, and tells the UI info about external API location and version 79 // information 80 OnSignerStartup(info StartupInfo) 81 } 82 83 // SignerAPI defines the actual implementation of ExternalAPI 84 type SignerAPI struct { 85 chainID *big.Int 86 am *accounts.Manager 87 UI SignerUI 88 validator *Validator 89 } 90 91 // Metadata about a request 92 type Metadata struct { 93 Remote string `json:"remote"` 94 Local string `json:"local"` 95 Scheme string `json:"scheme"` 96 } 97 98 // MetadataFromContext extracts Metadata from a given context.Context 99 func MetadataFromContext(ctx context.Context) Metadata { 100 m := Metadata{"NA", "NA", "NA"} // batman 101 102 if v := ctx.Value("remote"); v != nil { 103 m.Remote = v.(string) 104 } 105 if v := ctx.Value("scheme"); v != nil { 106 m.Scheme = v.(string) 107 } 108 if v := ctx.Value("local"); v != nil { 109 m.Local = v.(string) 110 } 111 return m 112 } 113 114 // String implements Stringer interface 115 func (m Metadata) String() string { 116 s, err := json.Marshal(m) 117 if err == nil { 118 return string(s) 119 } 120 return err.Error() 121 } 122 123 // types for the requests/response types between signer and UI 124 type ( 125 // SignTxRequest contains info about a Transaction to sign 126 SignTxRequest struct { 127 Transaction SendTxArgs `json:"transaction"` 128 Callinfo []ValidationInfo `json:"call_info"` 129 Meta Metadata `json:"meta"` 130 } 131 // SignTxResponse result from SignTxRequest 132 SignTxResponse struct { 133 //The UI may make changes to the TX 134 Transaction SendTxArgs `json:"transaction"` 135 Approved bool `json:"approved"` 136 Password string `json:"password"` 137 } 138 // ExportRequest info about query to export accounts 139 ExportRequest struct { 140 Address common.Address `json:"address"` 141 Meta Metadata `json:"meta"` 142 } 143 // ExportResponse response to export-request 144 ExportResponse struct { 145 Approved bool `json:"approved"` 146 } 147 // ImportRequest info about request to import an Account 148 ImportRequest struct { 149 Meta Metadata `json:"meta"` 150 } 151 ImportResponse struct { 152 Approved bool `json:"approved"` 153 OldPassword string `json:"old_password"` 154 NewPassword string `json:"new_password"` 155 } 156 SignDataRequest struct { 157 Address common.MixedcaseAddress `json:"address"` 158 Rawdata hexutil.Bytes `json:"raw_data"` 159 Message string `json:"message"` 160 Hash hexutil.Bytes `json:"hash"` 161 Meta Metadata `json:"meta"` 162 } 163 SignDataResponse struct { 164 Approved bool `json:"approved"` 165 Password string 166 } 167 NewAccountRequest struct { 168 Meta Metadata `json:"meta"` 169 } 170 NewAccountResponse struct { 171 Approved bool `json:"approved"` 172 Password string `json:"password"` 173 } 174 ListRequest struct { 175 Accounts []Account `json:"accounts"` 176 Meta Metadata `json:"meta"` 177 } 178 ListResponse struct { 179 Accounts []Account `json:"accounts"` 180 } 181 Message struct { 182 Text string `json:"text"` 183 } 184 StartupInfo struct { 185 Info map[string]interface{} `json:"info"` 186 } 187 ) 188 189 var ErrRequestDenied = errors.New("Request denied") 190 191 type errorWrapper struct { 192 msg string 193 err error 194 } 195 196 func (ew errorWrapper) String() string { 197 return fmt.Sprintf("%s\n%s", ew.msg, ew.err) 198 } 199 200 // NewSignerAPI creates a new API that can be used for Account management. 201 // ksLocation specifies the directory where to store the password protected private 202 // key that is generated when a new Account is created. 203 func NewSignerAPI(chainID int64, ksLocation string, ui SignerUI, abidb *AbiDb, lightKDF bool) *SignerAPI { 204 var ( 205 backends []accounts.Backend 206 n, p = keystore.StandardScryptN, keystore.StandardScryptP 207 ) 208 if lightKDF { 209 n, p = keystore.LightScryptN, keystore.LightScryptP 210 } 211 // support password based accounts 212 if len(ksLocation) > 0 { 213 backends = append(backends, keystore.NewKeyStore(ksLocation, n, p)) 214 } 215 return &SignerAPI{big.NewInt(chainID), accounts.NewManager(backends...), ui, NewValidator(abidb)} 216 } 217 218 // List returns the set of wallet this signer manages. Each wallet can contain 219 // multiple accounts. 220 func (api *SignerAPI) List(ctx context.Context) (Accounts, error) { 221 var accs []Account 222 for _, wallet := range api.am.Wallets() { 223 for _, acc := range wallet.Accounts() { 224 acc := Account{Typ: "Account", URL: wallet.URL(), Address: acc.Address} 225 accs = append(accs, acc) 226 } 227 } 228 result, err := api.UI.ApproveListing(&ListRequest{Accounts: accs, Meta: MetadataFromContext(ctx)}) 229 if err != nil { 230 return nil, err 231 } 232 if result.Accounts == nil { 233 return nil, ErrRequestDenied 234 235 } 236 return result.Accounts, nil 237 } 238 239 // New creates a new password protected Account. The private key is protected with 240 // the given password. Users are responsible to backup the private key that is stored 241 // in the keystore location thas was specified when this API was created. 242 func (api *SignerAPI) New(ctx context.Context) (accounts.Account, error) { 243 be := api.am.Backends(keystore.KeyStoreType) 244 if len(be) == 0 { 245 return accounts.Account{}, errors.New("password based accounts not supported") 246 } 247 resp, err := api.UI.ApproveNewAccount(&NewAccountRequest{MetadataFromContext(ctx)}) 248 249 if err != nil { 250 return accounts.Account{}, err 251 } 252 if !resp.Approved { 253 return accounts.Account{}, ErrRequestDenied 254 } 255 return be[0].(*keystore.KeyStore).NewAccount(resp.Password) 256 } 257 258 // logDiff logs the difference between the incoming (original) transaction and the one returned from the signer. 259 // it also returns 'true' if the transaction was modified, to make it possible to configure the signer not to allow 260 // UI-modifications to requests 261 func logDiff(original *SignTxRequest, new *SignTxResponse) bool { 262 modified := false 263 if f0, f1 := original.Transaction.From, new.Transaction.From; !reflect.DeepEqual(f0, f1) { 264 log.Info("Sender-account changed by UI", "was", f0, "is", f1) 265 modified = true 266 } 267 if t0, t1 := original.Transaction.To, new.Transaction.To; !reflect.DeepEqual(t0, t1) { 268 log.Info("Recipient-account changed by UI", "was", t0, "is", t1) 269 modified = true 270 } 271 if g0, g1 := original.Transaction.Gas, new.Transaction.Gas; g0 != g1 { 272 modified = true 273 log.Info("Gas changed by UI", "was", g0, "is", g1) 274 } 275 if g0, g1 := big.Int(original.Transaction.GasPrice), big.Int(new.Transaction.GasPrice); g0.Cmp(&g1) != 0 { 276 modified = true 277 log.Info("GasPrice changed by UI", "was", g0, "is", g1) 278 } 279 if v0, v1 := big.Int(original.Transaction.Value), big.Int(new.Transaction.Value); v0.Cmp(&v1) != 0 { 280 modified = true 281 log.Info("Value changed by UI", "was", v0, "is", v1) 282 } 283 if d0, d1 := original.Transaction.Data, new.Transaction.Data; d0 != d1 { 284 d0s := "" 285 d1s := "" 286 if d0 != nil { 287 d0s = common.ToHex(*d0) 288 } 289 if d1 != nil { 290 d1s = common.ToHex(*d1) 291 } 292 if d1s != d0s { 293 modified = true 294 log.Info("Data changed by UI", "was", d0s, "is", d1s) 295 } 296 } 297 if n0, n1 := original.Transaction.Nonce, new.Transaction.Nonce; n0 != n1 { 298 modified = true 299 log.Info("Nonce changed by UI", "was", n0, "is", n1) 300 } 301 return modified 302 } 303 304 // SignTransaction signs the given Transaction and returns it both as json and rlp-encoded form 305 func (api *SignerAPI) SignTransaction(ctx context.Context, args SendTxArgs, methodSelector *string) (*vntapi.SignTransactionResult, error) { 306 var ( 307 err error 308 result SignTxResponse 309 ) 310 msgs, err := api.validator.ValidateTransaction(&args, methodSelector) 311 if err != nil { 312 return nil, err 313 } 314 315 req := SignTxRequest{ 316 Transaction: args, 317 Meta: MetadataFromContext(ctx), 318 Callinfo: msgs.Messages, 319 } 320 // Process approval 321 result, err = api.UI.ApproveTx(&req) 322 if err != nil { 323 return nil, err 324 } 325 if !result.Approved { 326 return nil, ErrRequestDenied 327 } 328 // Log changes made by the UI to the signing-request 329 logDiff(&req, &result) 330 var ( 331 acc accounts.Account 332 wallet accounts.Wallet 333 ) 334 acc = accounts.Account{Address: result.Transaction.From.Address()} 335 wallet, err = api.am.Find(acc) 336 if err != nil { 337 return nil, err 338 } 339 // Convert fields into a real transaction 340 var unsignedTx = result.Transaction.toTransaction() 341 342 // The one to sign is the one that was returned from the UI 343 signedTx, err := wallet.SignTxWithPassphrase(acc, result.Password, unsignedTx, api.chainID) 344 if err != nil { 345 api.UI.ShowError(err.Error()) 346 return nil, err 347 } 348 349 rlpdata, err := rlp.EncodeToBytes(signedTx) 350 response := vntapi.SignTransactionResult{Raw: rlpdata, Tx: signedTx} 351 352 // Finally, send the signed tx to the UI 353 api.UI.OnApprovedTx(response) 354 // ...and to the external caller 355 return &response, nil 356 357 } 358 359 // Sign calculates an VNT ECDSA signature for: 360 // keccack256("\x19Hubble Signed Message:\n" + len(message) + message)) 361 // 362 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 363 // where the V value will be 27 or 28 for legacy reasons. 364 // 365 // The key used to calculate the signature is decrypted with the given password. 366 // 367 // https://github.com/vntchain/go-vnt/wiki/Management-APIs#personal_sign 368 func (api *SignerAPI) Sign(ctx context.Context, addr common.MixedcaseAddress, data hexutil.Bytes) (hexutil.Bytes, error) { 369 sighash, msg := SignHash(data) 370 // We make the request prior to looking up if we actually have the account, to prevent 371 // account-enumeration via the API 372 req := &SignDataRequest{Address: addr, Rawdata: data, Message: msg, Hash: sighash, Meta: MetadataFromContext(ctx)} 373 res, err := api.UI.ApproveSignData(req) 374 375 if err != nil { 376 return nil, err 377 } 378 if !res.Approved { 379 return nil, ErrRequestDenied 380 } 381 // Look up the wallet containing the requested signer 382 account := accounts.Account{Address: addr.Address()} 383 wallet, err := api.am.Find(account) 384 if err != nil { 385 return nil, err 386 } 387 // Assemble sign the data with the wallet 388 signature, err := wallet.SignHashWithPassphrase(account, res.Password, sighash) 389 if err != nil { 390 api.UI.ShowError(err.Error()) 391 return nil, err 392 } 393 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 394 return signature, nil 395 } 396 397 // EcRecover returns the address for the Account that was used to create the signature. 398 // Note, this function is compatible with core_sign and personal_sign. As such it recovers 399 // the address of: 400 // hash = keccak256("\x19Hubble Signed Message:\n"${message length}${message}) 401 // addr = ecrecover(hash, signature) 402 // 403 // Note, the signature must conform to the secp256k1 curve R, S and V values, where 404 // the V value must be be 27 or 28 for legacy reasons. 405 // 406 // https://github.com/vntchain/go-vnt/wiki/Management-APIs#personal_ecRecover 407 func (api *SignerAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) { 408 if len(sig) != 65 { 409 return common.Address{}, fmt.Errorf("signature must be 65 bytes long") 410 } 411 if sig[64] != 27 && sig[64] != 28 { 412 return common.Address{}, fmt.Errorf("invalid VNT signature (V is not 27 or 28)") 413 } 414 sig[64] -= 27 // Transform yellow paper V from 27/28 to 0/1 415 hash, _ := SignHash(data) 416 rpk, err := crypto.SigToPub(hash, sig) 417 if err != nil { 418 return common.Address{}, err 419 } 420 return crypto.PubkeyToAddress(*rpk), nil 421 } 422 423 // SignHash is a helper function that calculates a hash for the given message that can be 424 // safely used to calculate a signature from. 425 // 426 // The hash is calculated as 427 // keccak256("\x19Hubble Signed Message:\n"${message length}${message}). 428 // 429 // This gives context to the signed message and prevents signing of transactions. 430 func SignHash(data []byte) ([]byte, string) { 431 msg := fmt.Sprintf("\x19Hubble Signed Message:\n%d%s", len(data), data) 432 return crypto.Keccak256([]byte(msg)), msg 433 } 434 435 // Export returns encrypted private key associated with the given address in web3 keystore format. 436 func (api *SignerAPI) Export(ctx context.Context, addr common.Address) (json.RawMessage, error) { 437 res, err := api.UI.ApproveExport(&ExportRequest{Address: addr, Meta: MetadataFromContext(ctx)}) 438 439 if err != nil { 440 return nil, err 441 } 442 if !res.Approved { 443 return nil, ErrRequestDenied 444 } 445 // Look up the wallet containing the requested signer 446 wallet, err := api.am.Find(accounts.Account{Address: addr}) 447 if err != nil { 448 return nil, err 449 } 450 if wallet.URL().Scheme != keystore.KeyStoreScheme { 451 return nil, fmt.Errorf("Account is not a keystore-account") 452 } 453 return ioutil.ReadFile(wallet.URL().Path) 454 } 455 456 // Import tries to import the given keyJSON in the local keystore. The keyJSON data is expected to be 457 // in web3 keystore format. It will decrypt the keyJSON with the given passphrase and on successful 458 // decryption it will encrypt the key with the given newPassphrase and store it in the keystore. 459 func (api *SignerAPI) Import(ctx context.Context, keyJSON json.RawMessage) (Account, error) { 460 be := api.am.Backends(keystore.KeyStoreType) 461 462 if len(be) == 0 { 463 return Account{}, errors.New("password based accounts not supported") 464 } 465 res, err := api.UI.ApproveImport(&ImportRequest{Meta: MetadataFromContext(ctx)}) 466 467 if err != nil { 468 return Account{}, err 469 } 470 if !res.Approved { 471 return Account{}, ErrRequestDenied 472 } 473 acc, err := be[0].(*keystore.KeyStore).Import(keyJSON, res.OldPassword, res.NewPassword) 474 if err != nil { 475 api.UI.ShowError(err.Error()) 476 return Account{}, err 477 } 478 return Account{Typ: "Account", URL: acc.URL, Address: acc.Address}, nil 479 }