Skip to content

Commit

Permalink
some more refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
SmithSamuelM committed Mar 26, 2024
1 parent bcb6f17 commit 82d3491
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 119 deletions.
12 changes: 6 additions & 6 deletions src/keri/core/coring.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def sizeify(ked, kind=None, version=Version):
raise ValueError("Missing or empty version string in key event "
"dict = {}".format(ked))

proto, vrsn, knd, size = deversify(ked["v"]) # extract kind and version
proto, vrsn, knd, size, _ = deversify(ked["v"]) # extract kind and version
if vrsn != version:
raise ValueError("Unsupported version = {}.{}".format(vrsn.major,
vrsn.minor))
Expand Down Expand Up @@ -3754,7 +3754,7 @@ def _serialize(clas, sad: dict, kind: str = None):
"""
knd = Serials.json
if 'v' in sad: # versioned sad
_, _, knd, _ = deversify(sad['v'])
_, _, knd, _, _ = deversify(sad['v'])

if not kind: # match logic of Serder for kind
kind = knd
Expand Down Expand Up @@ -5161,14 +5161,14 @@ def _inhale(self, raw):
loads and jumps of json use str whereas cbor and msgpack use bytes
"""
proto, version, kind, size = smell(raw)
if version != Version:
proto, vrsn, kind, size, _ = smell(raw)
if vrsn != Version:
raise VersionError("Unsupported version = {}.{}, expected {}."
"".format(version.major, version.minor, Version))
"".format(vrsn.major, vrsn.minor, Version))

ked = loads(raw=raw, size=size, kind=kind)

return ked, proto, kind, version, size
return ked, proto, kind, vrsn, size


def _exhale(self, ked, kind=None):
Expand Down
39 changes: 25 additions & 14 deletions src/keri/core/serdering.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def __init__(self, *pa, **kwa):
pass


def reap(self, ims, skip=0, native=False):
def reap(self, ims, genus=GenDex.KERI, gvrsn=Vrsn_2_0, native=False, skip=0):
"""Extract and return Serder subclass based on protocol type reaped from
version string inside serialized raw of Serder.
Expand All @@ -208,21 +208,32 @@ def reap(self, ims, skip=0, native=False):
Parameters:
ims (bytearray) of serialized incoming message stream. Assumes start
of stream is raw Serder.
skip (int): bytes to skip at front of ims. Useful when CESR native
serialization where skip is size of the message counter so smell
does need to see counter
genus (str): CESR genus code from stream parser.
Provides genus of enclosing stream top-level or nested group
gvrsn (Versionage): instance CESR genus code table version (Major, Minor)
Provides genus of enclosing stream top-level or nested group
native (bool): True means sniff determined may be CESR native message
so snuff instead of smell.
False means sniff determined not CESR native i.e
JSON, CBOR, MGPK field map. so use smell. Default False
skip (int): bytes to skip at front of ims. Useful when CESR native
serialization where skip is size of the message counter so smell
does need to see counter
"""
smellage = smell(memoryview(ims)[skip:]) # does not copy to skip
if native:
pass
#smellage = smell(memoryview(ims)[skip:]) # does not copy to skip

if smellage.protocol == Protocols.keri:
return SerderKERI(raw=ims, strip=True, smellage=smellage)
elif smellage.protocol == Protocols.acdc:
return SerderACDC(raw=ims, strip=True, smellage=smellage)
else:
smellage = smell(ims)

if smellage.proto == Protocols.keri:
return SerderKERI(raw=ims, strip=True, smellage=smellage,
genus=genus, gvrsn=gvrsn)
elif smellage.proto == Protocols.acdc:
return SerderACDC(raw=ims, strip=True, smellage=smellage,
genus=genus, gvrsn=gvrsn)
else:
raise ProtocolError(f"Unsupported protocol type = {smellage.proto}.")

Expand Down Expand Up @@ -768,7 +779,7 @@ def _verify(self):
raise ValidationError(f"Missing version string field in {sad}.")

# extract version string elements to verify consistency with attributes
proto, vrsn, kind, size = deversify(sad["v"])
proto, vrsn, kind, size, opt = deversify(sad["v"])
if self.proto != proto:
raise ValidationError(f"Inconsistent protocol={self.proto} in {sad}.")

Expand Down Expand Up @@ -827,7 +838,7 @@ def makify(self, sad, *, proto=None, vrsn=None, kind=None,
sproto = svrsn = skind = silk = None
if sad and 'v' in sad: # attempt to get from vs in sad
try: # extract version string elements as defaults if provided
sproto, svrsn, skind, _ = deversify(sad["v"])
sproto, svrsn, skind, _, _ = deversify(sad["v"])
except ValueError as ex:
pass
else:
Expand Down Expand Up @@ -1023,9 +1034,9 @@ def _inhale(self, raw, *, smellage=None):
"""
if smellage: # passed in so don't need to smell raw again
proto, vrsn, kind, size = smellage # tuple unpack
proto, vrsn, kind, size, gvrsn = smellage # tuple unpack
else: # not passed in so smell raw
proto, vrsn, kind, size = smell(raw)
proto, vrsn, kind, size, gvrsn = smell(raw)

sad = self.loads(raw=raw, size=size, kind=kind)
# ._gvrsn may be set in loads when CESR native deserialization provides _gvrsn
Expand Down Expand Up @@ -1117,7 +1128,7 @@ def _exhale(self, sad):
raise SerializeError(f"Missing version string field in {sad}.")

# extract elements so can replace size element but keep others
proto, vrsn, kind, size = deversify(sad["v"])
proto, vrsn, kind, size, opt = deversify(sad["v"])

raw = self.dumps(sad, kind)

Expand Down
35 changes: 18 additions & 17 deletions src/keri/kering.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,15 @@

"""
Smellage (results of smelling a version string such as in a Serder)
protocol (str): protocol type value of Protocols examples 'KERI', 'ACDC'
version (Versionage): protocol version namedtuple (major, minor) of ints
proto (str): protocol type value of Protocols examples 'KERI', 'ACDC'
vrsn (Versionage): protocol version namedtuple (major, minor) of ints
kind (str): serialization value of Serials examples 'JSON', 'CBOR', 'MGPK'
size (int | Versionage): int size of raw serialization or
genus version namedtuple (major, minor) of ints
size (int): int size of raw serialization or
gvrsn (None | Versionage): optional default is None
For CESR native genus version namedtuple (major, minor) of ints
"""
Smellage = namedtuple("Smellage", "protocol version kind size")
Smellage = namedtuple("Smellage", "proto vrsn kind size gvrsn", defaults=(None, ))

def rematch(match):
"""
Expand All @@ -95,9 +96,9 @@ def rematch(match):
"minor2",
"kind2",
"size2")
protocol = proto.decode("utf-8")
if protocol not in Protocols:
raise ProtocolError(f"Invalid protocol type = {protocol}.")
proto = proto.decode("utf-8")
if proto not in Protocols:
raise ProtocolError(f"Invalid protocol={proto}.")
vrsn = Versionage(major=b64ToInt(major), minor=b64ToInt(minor))
if vrsn.major < 2: # version2 vs but major < 2
raise VersionError(f"Incompatible {vrsn=} with version string.")
Expand All @@ -113,9 +114,9 @@ def rematch(match):
"minor1",
"kind1",
"size1")
protocol = proto.decode("utf-8")
if protocol not in Protocols:
raise ProtocolError(f"Invalid protocol type = {protocol}.")
proto = proto.decode("utf-8")
if proto not in Protocols:
raise ProtocolError(f"Invalid protocol={proto}.")
vrsn = Versionage(major=int(major, 16), minor=int(minor, 16))
if vrsn.major > 1: # version1 vs but major > 1
raise VersionError(f"Incompatible {vrsn=} with version string.")
Expand All @@ -128,7 +129,7 @@ def rematch(match):
else:
raise VersionError(f"Bad rematch.")

return Smellage(protocol=protocol, version=vrsn, kind=kind, size=size)
return Smellage(proto=proto, vrsn=vrsn, kind=kind, size=size)


def versify(protocol=Protocols.keri, version=Version, kind=Serials.json, size=0):
Expand Down Expand Up @@ -221,15 +222,15 @@ def snatch(match, size=0):
regular expressions work with memoryview objects not just bytes or
bytearrays
"""
if len(full) == VER0FULLSPAN:
if len(full) == VFFULLSPAN:
proto, major, minor, gmajor, gminor = match.group("proto0",
"major0",
"minor0",
"gmajor0",
"gminor0")
protocol = proto.decode("utf-8")
if protocol not in Protocols:
raise ProtocolError(f"Invalid protocol type = {protocol}.")
proto = proto.decode("utf-8")
if proto not in Protocols:
raise ProtocolError(f"Invalid protocol type = {proto}.")
vrsn = Versionage(major=b64ToInt(major), minor=b64ToInt(minor))
if vrsn.major < 2: # version2 vs but major < 2
raise VersionError(f"Incompatible {vrsn=} with version string.")
Expand All @@ -243,7 +244,7 @@ def snatch(match, size=0):
else:
raise VersionError(f"Bad snatch.")

return Smellage(protocol=protocol, version=vrsn, kind=kind, size=size)
return Smellage(proto=proto, vrsn=vrsn, kind=kind, size=size, gvrsn=gvrsn)


def snuff(raw, size=0):
Expand Down
55 changes: 2 additions & 53 deletions tests/core/test_serdering.py
Original file line number Diff line number Diff line change
Expand Up @@ -2616,7 +2616,7 @@ def test_serdery():
b'kj_S6LJQDRNOiGohW327FMA6D2","s":""}Not a Serder here or there or'
b' anywhere.')

serdery = Serdery(version=Version)
serdery = Serdery()

serder = serdery.reap(ims)
assert isinstance(serder, SerderKERI)
Expand All @@ -2636,58 +2636,7 @@ def test_serdery():

"""End Test"""

def test_serdery_noversion():
"""Test Serdery unsupported version"""
#Create incoming message stream for Serdery to reap

serder = SerderKERI(makify=True, ilk=kering.Ilks.ixn, verify=False) # make with defaults
sad = serder.sad
pre = "EDGnGYIa5obfFUhxcAuUmM4fJyeRYj2ti3KGf87Bc70J"
sad['i'] = pre
sad['s'] = 2
sad['a'] = []
serderKeri = SerderKERI(sad=sad, makify=True)
assert serderKeri.verify()

ims = bytearray(serderKeri.raw)

serder = SerderACDC(makify=True, proto=Protocols.acdc, verify=False) # make defaults for ACDC
sad = serder.sad
isr = 'EO8CE5RH1X8QJwHHhPkj_S6LJQDRNOiGohW327FMA6D2'
sad['i'] = isr
serderAcdc = SerderACDC(sad=sad, makify=True)
assert serderAcdc.verify()

ims.extend(serderAcdc.raw)

ims.extend(b"Not a Serder here or there or anywhere.")

assert ims == bytearray(b'{"v":"KERI10JSON00009d_","t":"ixn","d":"EPTgL0UEOa8xUWBqghryJYML'
b'Od2eYjmclndQN4bArjSf","i":"EDGnGYIa5obfFUhxcAuUmM4fJyeRYj2ti3KGf'
b'87Bc70J","s":2,"p":"","a":[]}{"v":"ACDC10JSON000086_","d":"EJxJ1'
b'GB8oGD4JAH7YpiMCSWKDV3ulpt37zg9vq1QnOh_","i":"EO8CE5RH1X8QJwHHhP'
b'kj_S6LJQDRNOiGohW327FMA6D2","s":""}Not a Serder here or there or'
b' anywhere.')

serdery = Serdery() # effective version is None

serder = serdery.reap(ims)
assert isinstance(serder, SerderKERI)
assert serder.raw == serderKeri.raw

serder = serdery.reap(ims)
assert isinstance(serder, SerderACDC)
assert serder.raw == serderAcdc.raw

assert ims == bytearray(b'Not a Serder here or there or anywhere.')

with pytest.raises(kering.VersionError):
serder = serdery.reap(ims)

assert ims == bytearray(b'Not a Serder here or there or anywhere.')


"""End Test"""


if __name__ == "__main__":
Expand All @@ -2710,4 +2659,4 @@ def test_serdery_noversion():
test_serderacdc()
test_serder_v2()
test_serdery()
test_serdery_noversion()

Loading

0 comments on commit 82d3491

Please sign in to comment.