nim-nitro/nitro/wallet.nim

57 lines
1.6 KiB
Nim
Raw Normal View History

2021-03-17 12:53:30 +01:00
import std/tables
2021-03-09 16:53:15 +01:00
import ./basics
import ./keys
import ./protocol
2021-03-17 13:10:49 +01:00
import ./signedstate
2021-03-16 12:50:46 +01:00
import ./ledger
2021-03-09 16:53:15 +01:00
include questionable/errorban
export basics
export keys
2021-03-17 13:10:49 +01:00
export signedstate
2021-03-09 16:53:15 +01:00
type
Wallet* = object
key: PrivateKey
2021-03-17 13:10:49 +01:00
channels: Table[ChannelId, SignedState]
2021-03-17 12:53:30 +01:00
ChannelId* = Destination
2021-03-09 16:53:15 +01:00
2021-03-17 12:22:00 +01:00
func init*(_: type Wallet, key: PrivateKey): Wallet =
2021-03-09 16:53:15 +01:00
result.key = key
2021-03-17 12:22:00 +01:00
func address*(wallet: Wallet): EthAddress =
2021-03-09 16:53:15 +01:00
wallet.key.toPublicKey.toAddress
2021-03-17 13:10:49 +01:00
func `[]`*(wallet: Wallet, channel: ChannelId): ?SignedState =
2021-03-17 12:53:30 +01:00
wallet.channels[channel].catch.option
2021-03-17 13:10:49 +01:00
func sign(wallet: Wallet, state: SignedState): SignedState =
var signed = state
signed.signatures &= @{wallet.address: wallet.key.sign(state.state)}
2021-03-16 12:50:46 +01:00
signed
2021-03-17 13:10:49 +01:00
func createChannel(wallet: var Wallet, state: SignedState): ChannelId =
let signed = wallet.sign(state)
2021-03-17 12:53:30 +01:00
let id = getChannelId(signed.state.channel)
wallet.channels[id] = signed
id
2021-03-16 12:50:46 +01:00
2021-03-17 12:22:00 +01:00
func openLedgerChannel*(wallet: var Wallet,
2021-03-15 16:19:29 +01:00
hub: EthAddress,
chainId: UInt256,
nonce: UInt48,
asset: EthAddress,
2021-03-17 12:53:30 +01:00
amount: UInt256): ChannelId =
2021-03-17 13:10:49 +01:00
let state = startLedger(wallet.address, hub, chainId, nonce, asset, amount)
wallet.createChannel(state)
2021-03-16 12:50:46 +01:00
func acceptChannel*(wallet: var Wallet, signed: SignedState): ?!ChannelId =
if not signed.hasParticipant(wallet.address):
2021-03-17 12:53:30 +01:00
return ChannelId.failure "wallet owner is not a participant"
2021-03-16 12:50:46 +01:00
if not verifySignatures(signed):
2021-03-17 12:53:30 +01:00
return ChannelId.failure "incorrect signatures"
2021-03-16 12:50:46 +01:00
wallet.createChannel(signed).success