Skip to content

Commit

Permalink
Merge pull request #531 from SmithSamuelM/dev
Browse files Browse the repository at this point in the history
More refactor of ksn as dataclass
  • Loading branch information
SmithSamuelM authored Jun 12, 2023
2 parents 68170d0 + 3b5bd17 commit b03ccf2
Show file tree
Hide file tree
Showing 9 changed files with 206 additions and 165 deletions.
26 changes: 14 additions & 12 deletions src/keri/app/cli/commands/rollback.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from keri import kering
from keri.app.cli.common import displaying, existing
from keri.core import coring
from keri.db import dbing
from keri.db import dbing, basing
from keri.help import helping
from keri.kering import ConfigurationError

Expand Down Expand Up @@ -64,7 +64,7 @@ def rollback(tymth, tock=0.0, **opts):
raise kering.ValidationError(f"top event at sequence number {hab.kever.sn} has been published to "
f"{len(wigs)} witnesses, unable to rollback.")

state = hby.db.states.get(keys=serder.pre)
ked = hby.db.states.getDict(keys=serder.pre)
pdig = hby.db.getKeLast(dbing.snKey(serder.preb, serder.sn - 1))

pDgKey = dbing.dgKey(serder.preb, bytes(pdig)) # get message
Expand All @@ -80,19 +80,21 @@ def rollback(tymth, tock=0.0, **opts):
hby.db.delKes(dbing.snKey(serder.preb, serder.sn))

seqner = coring.Number(num=serder.sn - 1)
fner = coring.Number(numh=state.ked['f'])
fner = coring.Number(numh=ked['f'])
fner = coring.Number(num=fner.num - 1)

# Update the only items in state that will change after rolling back an ixn
state.ked['s'] = seqner.numh
state.ked['et'] = pserder.ked['t']
state.ked['p'] = pserder.ked['p']
state.ked['d'] = pserder.said
state.ked['f'] = fner.numh
state.ked['dt'] = helping.nowIso8601()

state = coring.Serder(ked=state.ked)
hby.db.states.pin(keys=hab.pre, val=state)
ked['s'] = seqner.numh
ked['et'] = pserder.ked['t']
ked['p'] = pserder.ked['p']
ked['d'] = pserder.said
ked['f'] = fner.numh
ked['dt'] = helping.nowIso8601()

state = coring.Serder(ked=ked)
hby.db.states.pin(keys=hab.pre,
val=helping.datify(basing.KeyStateRecord,
state.ked))

# Refresh all habs to reload this one
hby.db.reload()
Expand Down
4 changes: 2 additions & 2 deletions src/keri/app/habbing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1237,9 +1237,9 @@ def interact(self, *, data=None):
self.kvy.processEvent(serder=serder, sigers=sigers)
except MissingSignatureError:
pass
except Exception:
except Exception as ex:
raise kering.ValidationError("Improper Habitat interaction for "
"pre={}.".format(self.pre))
"pre={}.".format(self.pre)) from ex

return msg

Expand Down
20 changes: 15 additions & 5 deletions src/keri/core/eventing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from dataclasses import dataclass, astuple
from urllib.parse import urlsplit
from math import ceil
from ordered_set import OrderedSet as oset
from ordered_set import OrderedSet as oset
from hio.help import decking

from . import coring
Expand All @@ -21,7 +21,7 @@
from .. import kering
from ..db import basing, dbing
from ..db.dbing import dgKey, snKey, fnKey, splitKeySN, splitKey
from ..help import helping

from ..kering import (MissingEntryError,
ValidationError, MissingSignatureError,
MissingWitnessSignatureError, UnverifiedReplyError,
Expand All @@ -32,6 +32,8 @@
from ..kering import (ICP_LABELS, DIP_LABELS, ROT_LABELS, DRT_LABELS, IXN_LABELS,
KSN_LABELS, RPY_LABELS)

from ..help import helping

logger = help.ogler.getLogger()

EscrowTimeoutPS = 3600 # seconds for partial signed escrow timeout
Expand Down Expand Up @@ -1033,6 +1035,7 @@ def state(pre,
KeyStateDict:
{
"v": "KERI10JSON00011c_",
"vn": []1,0],
"i": "EaU6JR2nmwyZ-i0d8JZAoTNZH3ULvYAfSVPzhzS6b5CM",
"s": "2":,
"p": "EYAfSVPzhzZ-i0d8JZS6b5CMAoTNZH3ULvaU6JR2nmwy",
Expand Down Expand Up @@ -1143,6 +1146,7 @@ def state(pre,


ksd = dict(v=vs, # version string
vn=list(version), # version number as list [major, minor]
i=pre, # qb64 prefix
s=sner.numh, # lowercase hex string no leading zeros
p=pig,
Expand Down Expand Up @@ -1701,7 +1705,9 @@ def __init__(self, *, state=None, serder=None, sigers=None, wigers=None,
if fn is not None: # first is non-idempotent for fn check mode fn is None
self.fner = Number(num=fn)
self.dater = Dater(dts=dts)
self.db.states.pin(keys=self.prefixer.qb64, val=self.state())
self.db.states.pin(keys=self.prefixer.qb64,
val=helping.datify(basing.KeyStateRecord,
self.state().ked))


@property
Expand Down Expand Up @@ -2014,7 +2020,9 @@ def update(self, serder, sigers, wigers=None, delseqner=None, delsaider=None,
if fn is not None: # first is non-idempotent for fn check mode fn is None
self.fner = Number(num=fn)
self.dater = Dater(dts=dts)
self.db.states.pin(keys=self.prefixer.qb64, val=self.state())
self.db.states.pin(keys=self.prefixer.qb64,
val=helping.datify(basing.KeyStateRecord,
self.state().ked))


elif ilk == Ilks.ixn: # subsequent interaction event
Expand Down Expand Up @@ -2061,7 +2069,9 @@ def update(self, serder, sigers, wigers=None, delseqner=None, delsaider=None,
if fn is not None: # first is non-idempotent for fn check mode fn is None
self.fner = Number(num=fn)
self.dater = Dater(dts=dts)
self.db.states.pin(keys=self.prefixer.qb64, val=self.state())
self.db.states.pin(keys=self.prefixer.qb64,
val=helping.datify(basing.KeyStateRecord,
self.state().ked))

else: # unsupported event ilk so discard
raise ValidationError("Unsupported ilk = {} for evt = {}.".format(ilk, ked))
Expand Down
30 changes: 19 additions & 11 deletions src/keri/db/basing.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import shutil
from contextlib import contextmanager
from dataclasses import dataclass, asdict, field
from typing import Optional

import lmdb
from ordered_set import OrderedSet as oset
Expand All @@ -37,6 +36,7 @@

from .. import help


logger = help.ogler.getLogger()


Expand All @@ -58,10 +58,10 @@ def __getitem__(self, k):
except KeyError as ex:
if not self.db:
raise ex # reraise KeyError
if (state := self.db.states.get(keys=k)) is None:
if (ked := self.db.states.getDict(keys=k)) is None:
raise ex # reraise KeyError
try:
kever = eventing.Kever(state=state, db=self.db)
kever = eventing.Kever(state=coring.Serder(ked=ked), db=self.db)
except kering.MissingEntryError: # no kel event for keystate
raise ex # reraise KeyError
self.__setitem__(k, kever)
Expand Down Expand Up @@ -99,6 +99,8 @@ class KeyStateRecord: # baser.state
"""
v: str = '' # version string need to remove replace with vn below
vn: list[int] = field(default_factory=list) # version number [major, minor] round trip serializable
i: str ='' # identifier prefix qb64
s: str ='0' # sequence number of latest event in KEL as hex str
p: str ='' # prior event digest qb64
Expand All @@ -107,9 +109,9 @@ class KeyStateRecord: # baser.state
dt: str = '' # datetime of creation of state
et: str = '' # latest est evt packet type (ilk)
kt: str = '0' # signing threshold sith
k: list = field(default_factory=list) # signing key list qb64
k: list[str] = field(default_factory=list) # signing key list qb64
nt: str = '0' # next rotation threshold nsith
n: list = field(default_factory=list) # next rotation key digest list qb64
n: list[str] = field(default_factory=list) # next rotation key digest list qb64
bt: str = '0' # backer threshold hex num str
b: list = field(default_factory=list) # backer AID list qb64
c: list[str] = field(default_factory=list) # config trait list
Expand Down Expand Up @@ -738,8 +740,12 @@ def reopen(self, **kwa):

# events as ordered by first seen ordinals
self.fons = subing.CesrSuber(db=self, subkey='fons.', klas=coring.Seqner)
# Kever state
self.states = subing.SerderSuber(db=self, subkey='stts.') # key states
# Kever state made of KeyStateRecord
self.states = koming.Komer(db=self,
schema=KeyStateRecord,
subkey='stts.')
#self.states = subing.SerderSuber(db=self, subkey='stts.') # key states

self.wits = subing.CesrIoSetSuber(db=self, subkey="wits.", klas=coring.Prefixer)

# habitat application state keyed by habitat name, includes prefix
Expand Down Expand Up @@ -973,9 +979,10 @@ def reload(self):
"""
removes = []
for keys, data in self.habs.getItemIter():
if (state := self.states.get(keys=data.hid)) is not None:
if (ked := self.states.getDict(keys=data.hid)) is not None:
try:
kever = eventing.Kever(state=state, db=self,
kever = eventing.Kever(state=coring.Serder(ked=ked),
db=self,
prefixes=self.prefixes,
local=True)
except kering.MissingEntryError as ex: # no kel event for keystate
Expand All @@ -992,9 +999,10 @@ def reload(self):
# Load namespaced Habs
removes = []
for keys, data in self.nmsp.getItemIter():
if (state := self.states.get(keys=data.hid)) is not None:
if (ked := self.states.getDict(keys=data.hid)) is not None:
try:
kever = eventing.Kever(state=state, db=self,
kever = eventing.Kever(state=coring.Serder(ked=ked),
db=self,
prefixes=self.prefixes,
local=True)
except kering.MissingEntryError as ex: # no kel event for keystate
Expand Down
3 changes: 2 additions & 1 deletion src/keri/db/koming.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,8 @@ def getDict(self, keys: Union[str, Iterable]):
raise ExceptionHere
use val here
"""
return helping.dictify(self.get(keys))
val = self.get(keys)
return helping.dictify(val) if val is not None else None


def rem(self, keys: Union[str, Iterable]):
Expand Down
Loading

0 comments on commit b03ccf2

Please sign in to comment.