Skip to content

Commit

Permalink
add rpcs
Browse files Browse the repository at this point in the history
  • Loading branch information
qiweiii committed Oct 23, 2024
1 parent 37a021e commit d208337
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 2 deletions.
5 changes: 5 additions & 0 deletions Networking/Sources/Networking/Peer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,11 @@ public final class Peer<Handler: StreamHandler>: Sendable {
}
}
}

// there should be only one connection per peer
public func getPeersCount() -> Int {
impl.connections.value.byId.values.count
}
}

final class PeerImpl<Handler: StreamHandler>: Sendable {
Expand Down
4 changes: 4 additions & 0 deletions Node/Sources/Node/NetworkingProtocol/Network.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ public final class Network: Sendable {
public func listenAddress() throws -> NetAddr {
try peer.listenAddress()
}

public func getPeersCount() -> Int {
peer.getPeersCount()
}
}

struct HandlerDef: StreamHandler {
Expand Down
4 changes: 4 additions & 0 deletions Node/Sources/Node/NetworkingProtocol/NetworkManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,10 @@ public final class NetworkManager: Sendable {
)
}
}

public func getPeersCount() -> Int {
network.getPeersCount()
}
}

struct HandlerImpl: NetworkProtocolHandler {
Expand Down
3 changes: 1 addition & 2 deletions Node/Sources/Node/NodeDataSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ public final class NodeDataSource: DataSource {
}

public func getPeersCount() async throws -> Int {
// TODO: implememnt
0
networkManager.getPeersCount()
}
}
18 changes: 18 additions & 0 deletions RPC/Sources/RPC/Handlers/ChainHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ struct ChainHandler {

return [
"chain_getBlock": handler.getBlock,
"chain_getState": handler.getState,
]
}

Expand All @@ -32,4 +33,21 @@ struct ChainHandler {
]
}
}

func getState(request: JSONRequest) async throws -> any Encodable {
let hash = request.params?["hash"] as? String
if let hash {
guard let data = Data(fromHexString: hash), let data32 = Data32(data) else {
throw JSONError(code: -32602, message: "Invalid block hash")
}
let state = try await source.getState(hash: data32)
// return state root for now
return state?.stateRoot.description
} else {
// return best block state by default
let block = try await source.getBestBlock()
let state = try await source.getState(hash: block.hash)
return state?.stateRoot.description
}
}
}

0 comments on commit d208337

Please sign in to comment.