Skip to content

Commit

Permalink
fix: handle overflow for TransactionId timestamp
Browse files Browse the repository at this point in the history
Signed-off-by: Ricky Saechao <[email protected]>
  • Loading branch information
RickyLB committed Feb 6, 2025
1 parent 54ee7a3 commit af431bb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ task submodule:install
protoc --swift_opt=Visibility=Public --swift_opt=FileNaming=PathToUnderscores --swift_out=./Sources/HederaProtobufs/Services --proto_path=./Sources/HederaProtobufs/Protos/services Sources/HederaProtobufs/Protos/services/*.proto

# generate GRPC (if needed)
protoc --grpc-swift_opt=Visibility=Public,Server=false --grpc-swift_out=./Sources/HederaProtobufs/Services --proto_path=./Sources/HederaProtobufs/Protos/services Sources/HederaProtobufs/HederaProtobufs/Protos/services/*.proto
protoc --grpc-swift_opt=Visibility=Public,Server=false --grpc-swift_out=./Sources/HederaProtobufs/Services --proto_path=./Sources/HederaProtobufs/Protos/services Sources/HederaProtobufs/Protos/services/*.proto
```

### Integration Tests
Expand Down
19 changes: 15 additions & 4 deletions Sources/Hedera/TransactionId.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public struct TransactionId: Sendable, Equatable, Hashable, ExpressibleByStringL
public let scheduled: Bool
public let nonce: Int32?

private static let lastTimestamp = DispatchQueue(label: "TransactionId.timestamp.queue", attributes: .concurrent)
private static var lastUsedTimestamp: UInt64 = 0

internal init(accountId: AccountId, validStart: Timestamp, scheduled: Bool = false, nonce: Int32? = nil) {
self.accountId = accountId
self.validStart = validStart
Expand All @@ -24,11 +27,19 @@ public struct TransactionId: Sendable, Equatable, Hashable, ExpressibleByStringL

/// Generates a new transaction ID for the given account ID.
public static func generateFrom(_ accountId: AccountId) -> Self {
let random = UInt64.random(in: 5_000_000_000..<8_000_000_000)

let validStart = Timestamp.now.subtracting(nanos: random)
let now = Timestamp.now.unixTimestampNanos

var validStart: UInt64 = 0
lastTimestamp.sync {
if now > lastUsedTimestamp {
lastUsedTimestamp = now
} else {
lastUsedTimestamp += 1_000_000_000
}
validStart = lastUsedTimestamp
}

return Self(accountId: accountId, validStart: validStart)
return Self(accountId: accountId, validStart: Timestamp(fromUnixTimestampNanos: validStart))
}

/// Generates a new transaction ID for chunks.
Expand Down

0 comments on commit af431bb

Please sign in to comment.