Repository navigation
Expand file tree
/
Copy pathApp.fs
More file actions
263 lines (236 loc) · 10.3 KB
/
Copy pathApp.fs
File metadata and controls
263 lines (236 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
module Index
open System.Collections.Generic
open BitcoinRpc
open Explora
open Explora.Api
open Explora.MempoolSpace
open Explora.Types
open Fable.Core
open Fable.Core.JsInterop
open Microsoft.FSharp.Core
open Browser
open Browser.Types
open Vis
open Graph
let requestTransaction (txId: string) (graphModel: GraphModel) =
promise {
let txNode = GraphModel.getNode txId graphModel
if txNode.IsSome then
return (Ok graphModel)
else
let! txResult = getTransaction txId
return
txResult
|> Result.bind(function
| ConfirmedTransaction tx ->Ok(addTransactionToGraph tx graphModel)
| UnconfirmedTransaction _ -> Error "The requested transaction is still unconfirmed")
}
let requestSpenderTransaction (txId: string) (index: int) (graphModel: GraphModel) =
promise {
let! spenderResult = Api.getSpenderTransaction txId index
match spenderResult with
| Ok (SpentConfirmed spender) -> return! requestTransaction spender.txid graphModel
| Ok (SpentUnconfirmed spender) -> return (Error "The utxo is unconfirmed and the data providers doesn't give us info about unconfirmed elements")
| Ok SpendingStatus.Unspent -> return (Error "The txo is unspent")
| Error msg -> return (Error msg)
}
let shortenString (s: string) (maxLenght: int)=
match s.Length with
| n when n <= maxLenght -> s
| _ -> $"{s.[0..(maxLenght/2)-1]}..{s.[s.Length-(maxLenght/2)-1..]}"
let formatAddress (addr: string option) =
addr |> Option.defaultValue "--"
let formatBTC (value: float) =
value.ToString("N8").TrimEnd('0').TrimEnd('.') + " ₿"
let createAddressTableRow address amount id =
$"""<tr data-address="{id}" class="clickable-row">
<td class="address">{formatAddress address}</td>
<td class="amount">{formatAmount amount}</td>
</tr>"""
let createDetailTableRow detail value =
$"""<tr>
<td class="detail-label">{detail}</td>
<td class="detail-value">{value}</td>
</tr>"""
let createTableSection (title: string) (rows: string) =
$"""
<thead>
<tr>
<th colspan="2">{title}</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
"""
let createTableForTransaction (tx: ConfirmedTransaction) =
let inputsHtml =
tx.vin
|> Seq.map (fun inp -> createAddressTableRow inp.prevOut.scriptPubKey.address inp.prevOut.value inp.txid)
|> String.concat ""
let outputsHtml =
tx.vout
|> Seq.mapi (fun i out -> createAddressTableRow out.scriptPubKey.address out.value $"{tx.txid}-{i}")
|> String.concat ""
let detailsHtml =
[
"Hash", $"<a href=https://mempool.space/tx/{tx.txid}>{tx.txid}</a>"
"Version", string tx.version
"Volume", tx.vin |> Seq.sumBy (_.prevOut.value) |> formatAmount
"Fee", formatAmount tx.fee
"BlockHash", $"<a href=https://mempool.space/block/{tx.blockhash}>{tx.blockhash}</a>"
"BlockTime", string tx.blocktime
"Vsize", string tx.vsize
"Locktime", string tx.locktime
]
|> Seq.map (fun (d, v) -> createDetailTableRow d v)
|> String.concat ""
$"""
<table class="tx-details">
{createTableSection $"Details" detailsHtml}
</table>
<table class="tx-details">
{createTableSection $"Inputs ({tx.vin.Length})" inputsHtml}
{createTableSection $"Outputs ({tx.vout.Length})" outputsHtml}
</table>
"""
// Initialize application
let init() =
// Create graph container
let container = document.getElementById("mynetwork")
let txDetails = document.getElementById("tx-details")
// Create HTML structure
let graph = createGraph container
let graphModelHistory = Stack<GraphModel>()
graphModelHistory.Push { Nodes = []; Edges = []; Pending = [] }
let getCurrentGraphModel () =
graphModelHistory.Peek ()
let updateGraphModel (newGraphModelResult : Result<GraphModel,string>) =
match newGraphModelResult with
| Ok newGraphModel ->
graphModelHistory.Push newGraphModel
update graph newGraphModel
| Error msg -> window.alert msg
// Every address already on the map, except the ones behind the inputs being ranked: those are
// the candidates, and counting them would make every source look reused.
let knownAddresses (tx: ConfirmedTransaction) (graphModel: GraphModel) =
graphModel
|> GraphModel.getTransactions
|> List.collect (fun loaded ->
let outputs = loaded.vout |> Array.toList |> List.choose (fun output -> output.scriptPubKey.address)
let inputs =
if loaded.txid = tx.txid then []
else loaded.vin |> Array.toList |> List.choose (fun input -> input.prevOut.scriptPubKey.address)
outputs @ inputs)
|> List.distinct
|> Array.ofList
// Loads the transactions behind the inputs, `SourcesPerExpansion` at a time: address reuse first,
// then largest first. What doesn't fit stays as a "+N" node next to the transaction;
// double-clicking it loads the next batch.
let expandSources (tx: ConfirmedTransaction) =
promise {
let mutable graphModel = getCurrentGraphModel()
let loadedIds = graphModel.Nodes |> List.map (fun node -> node.Id) |> Array.ofList
let ranked = rankSources tx.vin loadedIds (knownAddresses tx graphModel) |> List.ofArray
let batch, rest = List.splitAt (min SourcesPerExpansion ranked.Length) ranked
for (sourceTxId, _) in batch do
let! txResult = requestTransaction sourceTxId graphModel
graphModel <-
match txResult with
| Ok newGraphModel ->
update graph newGraphModel
newGraphModel
| _ -> graphModel
updateGraphModel (Ok (GraphModel.setPending tx.txid rest graphModel))
} |> Promise.start
let requestTransaction txid graphModel =
promise {
let! newGraphModelResult = requestTransaction txid graphModel
updateGraphModel(newGraphModelResult)
} |> Promise.start
let requestSpenderTransaction (txId: string) (index: int) (graphModel: GraphModel) =
promise {
let! newGraphModelResult = requestSpenderTransaction txId index graphModel
updateGraphModel(newGraphModelResult)
} |> Promise.start
let setupRowClickHandlers (graph : Graph) =
document
.querySelectorAll(".clickable-row")
|> JS.Constructors.Array.from
|> Seq.cast<HTMLElement>
|> Seq.iter (fun row ->
row.addEventListener("click", fun e ->
let id = row.getAttribute("data-address")
printfn "Clicked row with id: %s" id
match id.Split("-") with
| [|txid; vout|] -> requestSpenderTransaction txid (int vout) (getCurrentGraphModel())
| [|txid|] -> requestTransaction txid (getCurrentGraphModel())
| _ -> failwith "WFT!!"
))
// Add event listeners
document.getElementById("search-button").onclick <- fun _ ->
let txId = (document.getElementById("txId") :?> HTMLInputElement).value
requestTransaction txId (getCurrentGraphModel())
container.onkeypress <- fun k ->
match k.key with
| "m" -> updateGraphModel (Ok (toggleMarkSelected (getCurrentGraphModel())))
| "z" ->
if graphModelHistory.Count > 0 then
graphModelHistory.Pop() |> ignore
update graph (getCurrentGraphModel())
| _ -> ()
graph.network.on(NetworkEvents.HoverNode, fun ps -> ())
graph.network.on(NetworkEvents.BlurNode, fun ps -> ())
graph.network.on(NetworkEvents.DragStart, fun ps ->
graph.network.stopSimulation()
graph.network?physics?options?enabled <- false
)
graph.network.on(NetworkEvents.DragEnd, fun ps ->
graph.network?physics?options?enabled <- true
graph.network.startSimulation()
)
graph.network.on(NetworkEvents.SelectEdge, fun ps ->
let txoid = ps?edges |> Array.head
if ps?nodes |> Array.length = 0 then
getCurrentGraphModel()
|> GraphModel.getEdge txoid
|> Option.iter(fun edge ->
updateGraphModel (Ok (selectEdge edge (getCurrentGraphModel()))))
)
graph.network.on(NetworkEvents.SelectNode, fun ps ->
let txid = ps?nodes |> Array.head
getCurrentGraphModel()
|> GraphModel.getNode txid
|> Option.iter(fun node ->
match node.Metadata with
| U2.Case2 txMetadata ->
txDetails.innerHTML <- createTableForTransaction txMetadata.tx
if txDetails.classList.contains("hidden") then
txDetails.classList.toggle("hidden") |> ignore
setupRowClickHandlers graph
updateGraphModel (Ok (selectNode node (getCurrentGraphModel())))
| _ -> ())
)
graph.network.on(NetworkEvents.DeselectNode, fun ps ->
if txDetails.classList.contains("hidden") = false then
txDetails.classList.toggle("hidden") |> ignore
updateGraphModel (Ok (deselectAll (getCurrentGraphModel())))
)
graph.network.on(NetworkEvents.DoubleClick,
function
| Some o ->
let ps = o :?> {| nodes : string array |}
if ps.nodes.Length > 0 then
let graphModel = getCurrentGraphModel()
let clickedNodeId = ps.nodes[0]
// A "+N" node stands for the transaction it hangs from.
let txNodeId = GraphModel.pendingOwner clickedNodeId graphModel |> Option.defaultValue clickedNodeId
graphModel
|> GraphModel.getNode txNodeId
|> Option.iter (fun clickedNodeModel ->
match clickedNodeModel.Metadata with
| U2.Case2 txMetadata -> expandSources txMetadata.tx
| _ -> ())
| None -> ())
// Start the application
init()