Skip to content

Commit

Permalink
Add round-trip to ensure decoding from XDR works correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
Shaptic committed Mar 24, 2022
1 parent 468e7de commit cf15638
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
47 changes: 47 additions & 0 deletions txnbuild/preconditions.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,53 @@ func (cond *Preconditions) BuildXDR() xdr.Preconditions {
return xdrCond
}

// FromXDR fills in the precondition structure from an xdr.Precondition.
func (cond *Preconditions) FromXDR(precondXdr xdr.Preconditions) {
*cond = Preconditions{} // reset existing values

switch precondXdr.Type {
case xdr.PreconditionTypePrecondTime:
cond.Timebounds = NewTimebounds(
int64(precondXdr.TimeBounds.MinTime),
int64(precondXdr.TimeBounds.MaxTime),
)

case xdr.PreconditionTypePrecondV2:
inner := precondXdr.V2

if inner.TimeBounds != nil {
cond.Timebounds = NewTimebounds(
int64(inner.TimeBounds.MinTime),
int64(inner.TimeBounds.MaxTime),
)
}

if inner.LedgerBounds != nil {
cond.Ledgerbounds = &Ledgerbounds{
MinLedger: uint32(inner.LedgerBounds.MinLedger),
MaxLedger: uint32(inner.LedgerBounds.MaxLedger),
}
}

if inner.MinSeqNum != nil {
minSeqNum := int64(*inner.MinSeqNum)
cond.MinSequenceNumber = &minSeqNum
}

cond.MinSequenceNumberAge = inner.MinSeqAge
cond.MinSequenceNumberLedgerGap = uint32(inner.MinSeqLedgerGap)

if len(inner.ExtraSigners) > 0 {
cond.ExtraSigners = make([]xdr.SignerKey, len(inner.ExtraSigners))
copy(cond.ExtraSigners[:], inner.ExtraSigners)
}

case xdr.PreconditionTypePrecondNone:
default:
// panic?
}
}

// hasV2Conditions determines whether or not this has conditions on top of
// the (required) timebound precondition.
func (cond *Preconditions) hasV2Conditions() bool {
Expand Down
9 changes: 9 additions & 0 deletions txnbuild/preconditions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,15 @@ func TestPreconditions(t *testing.T) {
assert.NoError(t, err)

assert.Equal(t, expectedBytes, actualBytes)

actualXdr := xdr.Preconditions{}
err = actualXdr.UnmarshalBinary(actualBytes)
assert.NoError(t, err)
assert.Equal(t, xdrPrecond, actualXdr)

roundTripPrecond := Preconditions{}
roundTripPrecond.FromXDR(actualXdr)
assert.Equal(t, precond, roundTripPrecond)
})
}
}
Expand Down

0 comments on commit cf15638

Please sign in to comment.