Working light-client + WASM

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
This commit is contained in:
Alexandru Vasile committed 2023-06-16 18:17:31 +03:00
1 parent 600a5cd14c
commit 2765087ff9
12 files changed
+2179 -655

No files matched your search

Generated
+1093 -161
View File
File diff suppressed because it is too large. Load diff
+29 -3
View File
@@ -72,10 +72,36 @@ wabt = "0.10.0"
wasm-bindgen-test = "0.3.24"
which = "4.4.0"
# Light client support:
smoldot = { path = "/home/lexnv/workspace/smoldot/lib", default-features = false }
smoldot-light = { path = "/home/lexnv/workspace/smoldot/light-base", default-features = false }
smoldot-light-wasm = { path = "/home/lexnv/workspace/smoldot/wasm-node/rust", default-features = false }
# /Users/lexnv/Workspace/parity/smoldot
# smoldot = { version = "0.6.0", default-features = false }
# smoldot-light = { version = "0.6.0", default-features = false }
# smoldot-light-wasm = { version = "0.5.0", default-features = false }
smoldot = { git = "https://github.com/smol-dot/smoldot", rev = "cf211107" , default_features = false }
smoldot-light = { git = "https://github.com/smol-dot/smoldot", rev = "cf211107", default_features = false }
# smoldot = { path = "/Users/lexnv/Workspace/parity/smoldot/lib", default-features = false }
# smoldot-light = { path = "/Users/lexnv/Workspace/parity/smoldot/light-base", default-features = false }
instant = { version = "0.1.12", default-features = false }
tokio-util = "0.7.8"
# Needed for Websocket secure WASM connections.
web-sys = { version = "0.3.61", features = [ "BinaryType", "CloseEvent", "MessageEvent", "WebSocket"] }
wasm-bindgen = "0.2.84"
send_wrapper = "0.6.0"
js-sys = "0.3.61"
websocket = "0.26.5"
# smoldot = { path = "/home/lexnv/workspace/smoldot/lib", default-features = false }
# smoldot-light = { path = "/home/lexnv/workspace/smoldot/light-base", default-features = false }
# smoldot-light-wasm = { path = "/home/lexnv/workspace/smoldot/wasm-node/rust", default-features = false }
wasm-bindgen-futures = { version = "0.4.19" }
futures-timer = { version = "3" }
gloo-net = { version = "0.2.6", default-features = false, features = ["json", "websocket"] }
+7 -1
View File
@@ -59,7 +59,7 @@
"0x31a3a2ce3603138b8b352e8f192ca55a4e7b9012096b41c4eb3aaf947f6ea429": "0x0000",
"0x3a2d6c9353500637d8f8e3e0fa0bb1c54e7b9012096b41c4eb3aaf947f6ea429": "0x0400",
"0x3a2d6c9353500637d8f8e3e0fa0bb1c5ba7fb8745735dc3be2a2c61a72c39e78": "0x00",
"0x3a636f6465": "0x52bc537646db8e0528b52ffd00589cb5042e14c6d513521028ee6a3a438e7810e4a374710cf1012713711870d2639b4c52cd3a9cea8c86f02ade7fffb99fe9dc8e4ba646010001100520bae72af5f67760a853e7018308937bb01394fbf8dbdade6d6d6fb9654a3205b116ce11ce12327e0a4eb26fee6ea9e20c27e9576421a589bb491adc2df5ceef0f5948694edd2de19ddfdf6221a589bb491adcf9fd608793a4376421a5497593bcbb25e7ceef17594869e26e9206774b78e7f7b7584869e26e9206774bbdf3fb5d2ca434713749833bbf9fc5271487bbf3899ac52723eece276aa20e9bc6b71f9c21b3d0fcd29f5bc6ff35ad9cd79f1f74f26b193f92d19f9fc50d68cbf8dd7e2de3276a16a170d59d4fd444cd24b78c9f636d8fc6cb446e3ddb0c901be4a1713e3faf9618d121d0220dd612334bb65812c592324b3cb08487253d0891216487d019426508bd198243888e21dcd00886a886e4189a63e88d213186ae18dac0900c43648688183a63c8862123866a10c243088e21a82132868610a262c88bd01b42770cad215425b4c7500884fa101ac1100d437108f13154c6d01d4222107242c80c212a211008b92194871016425708752164859094901e427108d5219485901c425a0c9d2094137a622809a13484da186a33f4c59010436e0c8d3194851013425f08792114c69015426008ad3154c4d0114263082531e485101b424d0885404809213184dc0c490dad115a62c80e256b9450a1a408253f2839a38407253e28a941090d4ac82899410917254f4abe249143090a49e8483202256094a4a0c485247d24e123c91e49f4502283921892dc91c48e246f92d4a1e404251950c242123792bcf1738412314a7049e6a0a9a14541938296038a03080ea03780dca0b140f5a0a9005407901d4072d06aa0d140db006d069a0c3432b418681aa0c1407b81e602ad05a03480d0a0d940e300cd0b501f407c00ed01a407501e407800bd01ba03e80c2010004d01994133432b43db81a6032d071a0eb40ed06ea041d1bad04ea071a1e180aa80d8007101b405101540580049015901a4055015404400f5006404d01040470015018404501a202780d4007d00a805a01f80ce003d017d01720242e1878d9f10fcb401740310d4cf087ee6f8c9e3678d1f3a7efaf861f3a3819f207e80f8c9c04f0f3f667ec2fc70414207923e90bcd18d4142061211203103c91a48d8403285c40b24402041f3e3c50f1a243320e982840c122e47f440d201243720c901090e48bec4ac88d9103b22c60259e6080f476a3832c3111982b080440ed08b8f17960e1d162e78e382392e18e382105480c5056c5cd0c6056bc4ccc46240d206e9260685fdc1fa6059b06770dc7c382022b860870b6620419093c70f1872d69021187b38b2451133480d500f583086c030a4052454af343a35435ec0616348991c3ec832ba2874e8f8586869a08810b609191148e290b5d1d9230606b9c6103248dc0c89a18818313348357ea0918181030799861ca347091c15c4377a822092420f9a235cf4e8d093430b77a487233ee44811640c3945e1207db02087990eb30ecc6e980931c341ec624646940202079035808400889b590cb139661a38b2c78c03621647f2d04901c81bb30dc4e8888d60c5c7aa4af442dc02c887990db31d281eb11662577c7ac472af1c6442c83a208392d9104ba14818fd444311eb235647cc0e227cb09e6839e14cb184d0c9a3d582758248954ed50ca76307eb8bd10b91372c2b4839baa8510a2060b45428d2059030907c314ec18a02891b2c22c60eb08a60218103029d3b461c583cb098607de05504cb8997175915eb0ad611ac295e3896122c2a72f6c8d1a325438c87110c113d6869ac1a15acb122d0d1803d03490a360d1d18746cb05443d6d8388648d9110cc1c2c231c40a3bc71036560efbc6902c865c91a345ce163604b3dccc899911b3226644cc8e980d316362b68465c3b661440fab4505137ba247885523ee670957d56b891707ac0bb6856e091d3c6248e8f01113a3252696812260c4a2623dc488c06923c6440b85d80a2c3431326233bc7a88613146116b53c48bd814ad0cc43cf04221c6e61503d9068926b6a6b581181018e0101b820584eb8558184366209fc81862450c61e1250309e6080d476c789d60c11116a4b100091c1930c801031d8ae45004872135c4682802c5101962628a3c31440343c60c59c1dba3d54567041d06c9c6f844e378fd30e6c06a6381930b8617132f17c82f435c5e1ab063fcc9f16085e04710e313ac2e5a2a16c5900df81d48c4987b9046b0b860612154844b310486edc1f260cd741348ca8875b152810582981a7f2384044b0beb012461b460887d40a8cd5018212e5861744cbc8288dd8043c6cb03af312f1d902431b4c78b87ae85170eac2d5860e46c2047869c1972c82051e2b5c36b05191d437990470ce9f19aa1f100e20550ee65c3d09ba13086d80c61a164032c2f847a18a1682e0e870bcdab8598133f58c8b1a2c96049c584c8b96228cd2a05205f08f130a4c54b0c4b0d56162f32ac34869010d50c7521ab6348098bc648359b618ce3081e3a2ae8aca01303903880b4a1d3c28c86990c40d800ea02881c2e206249c48c0042049021809c59e9b1daa30b13f3e1e3822404af148cdcf17aa26fbc687825f1f2a1c81415cd9134ba4dcb05f287560d44f6f891e2d50429065d439af1fa62757829d141d189e99e70c1f163c70b88d79923678a40b562688169d1204ba3f3a6b542cd402b85161499819816dd1a24482809f302f3524188089a428bcb8b4bfda2d30750109d996e4a478f234f78143a732461e3670a1d387476d001a3e3824e181d1a2ab8a2022b746a58a2c5101f3a4f621c4273047161e681118e990f4a8e8839c5ba8c2ab43810dbc2081e396c80a8f1a32636063d4379a03ee4b830a398c18033021c3970a82a6013a4852129903c9069c43a10c381b5c6ccccac0692881f3d5e44bc84f8b9a365c3912e9468607c43a88a0bce18f5904004c6374aac1847408b22cfb41ee410a410fd86481f241aa31347d0e835312a624d90649067c49688a57921d10d114361741aa2c2900c0c11d3758870741f45689830000141a3620c41e761b3200226c80bae385c6f0065202605a4c21017807838a2c5912c84a418e202881bad2b5a48b46e1052a3bf68bdd051d165a035664421c6452b4ceba9e54587ccaa0f9d31a216621b110c9d176241f40a620d4888403284e74106a1448521340ce1c00c02e4d2381d3144ec609d31f96099414322091c49a8586c586b5855b0a25852b0d4b0a060e5584db0966025c14ac33282758635c44f14ac1f583eb07a682674325081148b0beb0bcbc993c3a36279e901c2e5812340f4b840caf0434cce1445dc0883587d6175a14d5141154574305287913c74a090dc810306e709c709c70b0e0a385f8cd8f18a8a79d122f3721a3fLine truncated
"0x3a636f6465": "0x52bc537646db8e0528b52ffd0058dca804feff059013501028cf4c3ab35d6022448e1827b6441ac253541db60db71682b3c33ab0e59161bca9cc22e8fc86df5b29bc460000d5a92e5be7d0b65f30c0d63acf677accf22f3e028fa06123b2f7267bef2d654a3205811689117c12970a77e7f7d370d1d3b45da701dcf9fd2c32a136db9d7fd42c32196d77fe511f75d833befde00c998be697feb465fc5ecfca79fdf94127bd96f11719fdf959d4805bc6efd66b19ff51b3d884bbeefca33e6a26b965fcecd35669bc3c0155cf6e03e4061983713e3f7f49ccf416105c5e49b6326021891f49ca243923091a49d23082220911498a48d24392aa243924c140921b925c498283512018e0615486d119467824b1199531d2c3680c0cce601088911a46801871196d311283411f46472411c208090cf43042c368090c00310a83c10730f8c36806232d465d8c6030a201033f3010c4880b067b18d560a484d10a464e241902832ea3348cc024b101833c9274c1808f241930b26130885115234130e800067618dd91e402465f92d060748311068c3e603444921f8c8c48c243121892bc90c487245a920061f447122c0c3890c48b51114964c0c00318d0912408a33c8cf64852439219927029f2a3e84c511f456f14b551c446d11a456a148551044651134551148929c2a1684cd197a2248a345024455116454614215134449110454414611505510444d10f453e1481295aa2e888a21c662d14ed5044a6a88a222c8a9828baa148071a20b4406882d0f2a0f140bba2ed40d38196015a0e341c6837d03040eb42b38176011a195a15b4286850d0bca0dd6853d0c6d0baa07141db82a6052d0bda1a34356869d0d0a09d412b43338356068d08da1034216858342a684cd096a029414b8286040d0ced089a11b42fb42c1a16b42b6856500dd0bcd0b2d0b4d05ca0ad40b3a2b140bb42c342b332c36326c78c6b66c72c8fd91db33d667eccf49881311b6426c88c033333b32c6658ccae9865cdbecc86981931db9ab5316362d6c46ccc4c8899133322665c8eb071e4cc913e8ee071048e235b47f23862c591278e5c710408fac591208e7c398275648823451cc9c0911c8cf861e48f590e46ce30d2849130469c00a1307285912c8cc461040e231b3022879131b3398c4061448922808c6c1489e3478a9f28624cc4be88dd01800d10611161239645111f8aec50844b111a7eb4a812740922238e7c60b463a78ba88f0b6c448008cd70c115a241846ab8a00a9120425c2e5881e80f211a88ba88021192e1022b447e08d9207481a02246346cbed81441c407911ca212313d88b220ca826520e6448c4c6c901814313e62626282c4e488a1113323568690ed078c228214b1213606110edf1514f8410120415db138885a2012c30f1744578aa011fb63689058072848e3081341821c59e2c70b2257437c50f0019f237660889919f2808f1b4774f071e266081f366270d02e9f2184aa5070a6c8057cf608fac3878e21ad233b541b91172e68c2f7f02162c76a888c055c0c61892d3124858d193b55436262670c3151d3c650103031865819ea01007c0cf160a3c6ab8ad8105f1143552d84e885f885102d3b5a8456888511044863d10f048109f212f42588081d3b74b874eed0c12368889d1f8282305244d00f468830f2059c42278f201f7680d809625c03f42228899812b132b13982e8d87121a803168f59848c0fa31f68d0b0379b317eaaf81913e401500c110d101943440d2262882c013e41248b0816168c3d82881544c80cb111b922874c8e1544a4081223288c202f82baa8804cd017415c048111a445840a9d29a814d50b221820d225a68158960752848d995591366c02b1018482352850030066c42b6264100141010b4784b0d980cd20b30d1451c3e70ba2206e6c4447d02d3e51f840e1f3c4901584b8f02386e8875813ae46501d36cb6661a728eac27198fd4144846bf1f910e322d675a4896f87182014f441c11e14e8f15dd9f8d16f50269c8c0f570c8919478b3962b3f980d113462d7c3650c047cd96110b568b9b198c7840c4c2a8aaafbe1b6e80b869c172d165be1c6ccc1cf9c1a68e100d231b3cebc3c1e68f1b177ce4a861e3c6062321ea16435c6cdc88d961c3019b3d6e3280c1194257849af8baf41245637c3a7c1710dbf01c6eaad808e25b0cfd30ed30c2c2a7070ad0b82122490c35626ac6d440511385cd1d3667be1e7cf8f83260c12016087273c5a80f235b2cf823890b5d85b865a4abc9185919f971c407233130a8e326080cca6070c78781245b3040237626f6c607c4f783110e4640d033361d18026207cc8e971dac234958324179582b3c3e6cb208e2f202b15504e9e175d98061a5f8c1c2626135f093058c039f151b2dbc3d60666cb47e6e3123bc3e82f8f03e10c3fab1a25a093a43c1b0f9c24261e385a7870d173659de1f5f15581c4176fc90b162ec133f57d86c61a908fa804d1730386cc4f856b029c33af1d9bc4182eeb0c1c213c45e6113066c8e2344d8301e209e1f417bd831176405f9f14385772676046c03b33a6ebc0861a1f161c488d18d310d224ce8e8118415d4032845d055100f449ad0d943478cce13748b9d2c4256313a002007ac0ea22fb3176eacba0b102931d380cd1c33288aa4d14a0c59a170c4b488b5b173e586861b2d3735188981280922304445d47060d6456c4c5156c846d846b8c68d0c5f101794b15a42596eb6c08ea0820855f9e86173068c0e9f2d21166278f8e4514405055c4606b9200bda456521c68198968d1d358ca040664f085989556123c7cf17366d50392a0f3758940b1b34766c3664d0407cc4f89922f6019b343e1e6254d8f421ba51afd8ac6153c6e60a70cc0c069b296c901852c52609212fd8fc70c48b8d0f363ddc8c89ad31dba2c68d990b312b2ed0c2cf381f4684f00fd4f010b4048c8a9d41463ac0dbd8c6b8056ac04806da0b230784b61c193352b113830d1b00c803007300600f00e81104044d0b374d04093196c9008b910ba319b0308c9210d2421013415814b9110323364547614444d1143731d828606f1839625403ac023605cc0a5a1791974683822c146869336e60f8d1c2a78d9b1d6cac00d9f8e9e24687700cef03d6819f2d7c7eb05b805544421021411ba4c780e1d0615c70c35c614607125b9f416407226e08c9123448101e3670dc54c13cd0e110d447a8158611cba3c81a498e48d282c8459c41d422920937004641648b215762415ce0c594a3a8075a1f45576119a11833324230845c40480d4264103283102e4268e81d40384032201560181009100b300b0bf600bb788003402d86ae8ab850c11b3e6fd4a44183450e11433a8869bcaef0b92316454c889d2ab12fb1db6c03a4c1c8078cf4e15980578886289a6376f50a9da55bd8792176451117b02a660d468628b2625ee00b63ea110b24e6c54fd64ccb11343e2c9fd5a7e5abe1Line truncated
"0x3a65787472696e7369635f696e646578": "0x00000000",
"0x3a6772616e6470615f617574686f726974696573": "0x010488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee0100000000000000",
"0x3d9cad2baf702e20b136f4c8900cd8024e7b9012096b41c4eb3aaf947f6ea429": "0x0100",
@@ -169,6 +169,12 @@
}
},
"id": "dev",
"lightSyncState": {
"babeEpochChanges": "0x04be9c86fab0726762f7afa87c57913c8df6ad3454345da1bf70f956cd2a015f670100000000210fc210000000008118c210000000008118c21000000000e121c21000000000000004be9c86fab0726762f7afa87c57913c8df6ad3454345da1bf70f956cd2a015f6701000000000000000000000000210fc21000000000600900000000000004d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d01000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000004000000000000000201000000000000008118c21000000000600900000000000004d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d010000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000040000000000000002",
"babeFinalizedBlockWeight": 1,
"finalizedBlockHeader": "0x4e1ef9781925d9ae357b112a5eac96b1476300e37d84f89208edb85ac35e05c204e0a9f75e946a0e2bee41afcd0db9a462b1412bc1d3939eb403429ae5873dccc232c86fd1464e61a85a45e91538a10007d8c623aa640d6e8d6fccb887c6872b360c0642414245b5010100000000210fc21000000000c291d291daf6962bd50082c775b3b0e65f3a9d8f06b0929f5c1e280b56e1de074c6d9561ad5257d0f28970abba3ac294ae3da40bd3ab1603b75374cc8e86ce00e13a1df108b88cee6b2b7381056d630053018d869966b93be58713c31be5e001044241424529010104d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d0100000000000000000000000000000000000000000000000000000000000000000000000000000005424142450101fa6086fc3ceb54ab86adeb8ccb1431ee3615645ad136bfa54c85f63f81514f2a5c9882b9b81184c9b7bc967952a5672e59b0d3408484616645cea9e58356018a",
"grandpaAuthoritySet": "0x0488dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee010000000000000000000000000000000001010000000000"
},
"name": "Development",
"properties": {
"tokenDecimals": 10
+38 -2
View File
@@ -46,10 +46,28 @@ unstable-metadata = []
# TODO: WE NEED smoldot-light/std to build in non-wasm environments!!
unstable-light-client = [
"smoldot",
"smoldot/std",
# "smoldot-light/std",
"smoldot-light",
# "futures-executor",
"smoldot-light-wasm",
# "smoldot-light-wasm",
"tokio-stream",
"tokio/sync",
"tokio/rt",
"futures-util",
# "wasm-bindgen-futures",
# "futures-timer/wasm-bindgen",
"tokio-util",
"websocket",
# "gloo-net",
]
unstable-light-client-wasm = [
"smoldot",
# "smoldot-light/std",
"smoldot-light",
# "futures-executor",
# "smoldot-light-wasm",
"tokio-stream",
"tokio/sync",
"tokio/rt",
@@ -57,6 +75,13 @@ unstable-light-client = [
"wasm-bindgen-futures",
"futures-timer/wasm-bindgen",
"gloo-net",
"instant/wasm-bindgen",
# Based on WebConnection file
"js-sys",
"send_wrapper",
"web-sys",
"wasm-bindgen",
]
[dependencies]
@@ -99,7 +124,18 @@ subxt-metadata = { workspace = true }
# Light client support:
smoldot = { workspace = true, optional = true }
smoldot-light = { workspace = true, optional = true }
smoldot-light-wasm = { workspace = true, optional = true }
instant = { workspace = true, optional = true }
tokio-util = { workspace = true, optional = true }
web-sys = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
js-sys = { workspace = true, optional = true }
send_wrapper = { workspace = true, optional = true }
websocket = { workspace = true, optional = true }
# smoldot-light-wasm = { workspace = true, optional = true }
wasm-bindgen-futures = { workspace = true, optional = true }
futures-timer = { workspace = true, optional = true }
gloo-net = { workspace = true, optional = true }
+12 -259
View File
@@ -35,7 +35,8 @@ use std::{
use tokio::sync::{mpsc, oneshot};
use tokio_stream::wrappers::ReceiverStream;
use smoldot_light_wasm::platform::Platform as WasmPlatform;
// use smoldot_light_wasm::platform::Platform as Platform;
use super::tokio_platform::TokioPlatform as Platform;
// use super::platform::Platform as MyPlatform;
@@ -46,7 +47,7 @@ struct LightClientInner {
/// Smoldot light client implementation that leverages the `AsyncStdTcpWebSocket`.
///
/// Note: `AsyncStdTcpWebSocket` is not wasm compatible.
client: smoldot_light::Client<WasmPlatform>,
client: smoldot_light::Client<Platform>,
/// The ID of the chain used to identify the chain protocol (ie. substrate).
///
/// Note: A single chain is supported for a client. This aligns with the subxt's
@@ -136,260 +137,6 @@ impl LightClientInner {
}
}
/// Must stop the execution immediately. The message is a UTF-8 string found in the memory of
/// the WebAssembly at offset `message_ptr` and with length `message_len`.
///
/// > **Note**: This function is typically implemented using `throw`.
///
/// After this function has been called, no further Wasm functions must be called again on
/// this Wasm virtual machine. Explanation below.
///
/// # About throwing and safety
///
/// Rust programs can be configured in two panicking modes: `abort`, or `unwind`. Safe or
/// unsafe Rust code must be written by keeping in mind that the execution of a function can
/// be suddenly interrupted by a panic, but can rely on the fact that this panic will either
/// completely abort the program, or unwind the stack. In the latter case, they can rely on
/// the fact that `std::panic::catch_unwind` will catch this unwinding and let them perform
/// some additional clean-ups.
///
/// This function is typically implemented using `throw`. However, "just" throwing a JavaScript
/// exception from within the implementation of this function is neither `abort`, because the
/// JavaScript could call into the Wasm again later, nor `unwind`, because it isn't caught by
/// `std::panic::catch_unwind`. By being neither of the two, it breaks the assumptions that
/// some Rust codes might rely on for either correctness or safety.
/// In order to solve this problem, we enforce that `panic` must behave like `abort`, and
/// forbid calling into the Wasm virtual machine again.
///
/// Beyond the `panic` function itself, any other FFI function that throws must similarly
/// behave like `abort` and prevent any further execution.
#[no_mangle]
pub extern "C" fn panic(message_ptr: u32, message_len: u32) {
let slice =
unsafe { std::slice::from_raw_parts(message_ptr as *const u8, message_len as usize) };
if let Ok(message) = std::str::from_utf8(slice) {
panic!("{message}");
}
}
/// Copies the entire content of the buffer with the given index to the memory of the
/// WebAssembly at offset `target_pointer`.
///
/// In situations where a buffer must be provided from the JavaScript to the Rust code, the
/// JavaScript must (prior to calling the Rust function that requires the buffer) assign a
/// "buffer index" to the buffer it wants to provide. The Rust code then calls the
/// [`buffer_size`] and [`buffer_copy`] functions in order to obtain the length and content
/// of the buffer.
#[no_mangle]
pub extern "C" fn buffer_copy(buffer_index: u32, target_pointer: u32) {}
/// Returns the size (in bytes) of the buffer with the given index.
///
/// See the documentation of [`buffer_copy`] for context.
#[no_mangle]
pub extern "C" fn buffer_size(buffer_index: u32) -> u32 {
0
}
/// The queue of JSON-RPC responses of the given chain is no longer empty.
///
/// This function is only ever called after [`json_rpc_responses_peek`] has returned a `len`
/// of 0.
///
/// This function might be called spuriously, however this behavior must not be relied upon.
#[no_mangle]
pub extern "C" fn json_rpc_responses_non_empty(chain_id: u32) {}
/// Client is emitting a log entry.
///
/// Each log entry is made of a log level (`1 = Error, 2 = Warn, 3 = Info, 4 = Debug,
/// 5 = Trace`), a log target (e.g. "network"), and a log message.
///
/// The log target and message is a UTF-8 string found in the memory of the WebAssembly
/// virtual machine at offset `ptr` and with length `len`.
#[no_mangle]
pub extern "C" fn log(
level: u32,
target_ptr: u32,
target_len: u32,
message_ptr: u32,
message_len: u32,
) {
let target_slice =
unsafe { std::slice::from_raw_parts(target_ptr as *const u8, target_len as usize) };
let target = std::str::from_utf8(target_slice).unwrap_or_else(|_| "cannot decode target");
let msg_slice =
unsafe { std::slice::from_raw_parts(message_ptr as *const u8, message_len as usize) };
let message = std::str::from_utf8(msg_slice).unwrap_or_else(|_| "cannot decode message");
println!("log level={level} target={target} message={message}");
}
/// Called when [`advance_execution`] should be executed again.
///
/// This function might be called from within [`advance_execution`], in which case
/// [`advance_execution`] should be called again immediately after it returns.
#[no_mangle]
pub extern "C" fn advance_execution_ready() {}
/// After at least `milliseconds` milliseconds have passed, [`timer_finished`] must be called.
///
/// It is not a logic error to call [`timer_finished`] *before* `milliseconds` milliseconds
/// have passed, and this will likely cause smoldot to restart a new timer for the remainder
/// of the duration.
///
/// When [`timer_finished`] is called, the value of the monotonic clock (in the WASI bindings)
/// must have increased by at least the given number of `milliseconds`.
///
/// If `milliseconds` is 0, [`timer_finished`] should be called as soon as possible.
///
/// `milliseconds` never contains a negative number, `NaN` or infinite.
#[no_mangle]
pub extern "C" fn start_timer(milliseconds: f64) {}
/// Must initialize a new connection that tries to connect to the given multiaddress.
///
/// The multiaddress is a UTF-8 string found in the WebAssembly memory at offset `addr_ptr`
/// and with `addr_len` bytes. The string is a multiaddress such as `/ip4/1.2.3.4/tcp/5/ws`.
///
/// The `id` parameter is an identifier for this connection, as chosen by the Rust code. It
/// must be passed on every interaction with this connection.
///
/// Returns 0 to indicate success, or 1 to indicate that an error happened. If an error is
/// returned, the `id` doesn't correspond to anything.
///
/// > **Note**: If you implement this function using for example `new WebSocket()`, please
/// > keep in mind that exceptions should be caught and turned into an error code.
///
/// If an error happened, assign a so-called "buffer index" (a `u32`) representing the buffer
/// containing the UTF-8 error message, then write this buffer index as little-endian to the
/// memory of the WebAssembly indicated by `error_buffer_index_ptr`. The Rust code will call
/// [`buffer_size`] and [`buffer_copy`] in order to obtain the content of this buffer. The
/// buffer index should remain assigned and buffer alive until the next time the JavaScript
/// code retains control. Then, write at location `error_buffer_index_ptr + 4` a `1` if the
/// error is caused by the address being forbidden or unsupported, and `0` otherwise. If no
/// error happens, nothing should be written to `error_buffer_index_ptr`.
///
/// At any time, a connection can be in one of the three following states:
///
/// - `Opening` (initial state)
/// - `Open`
/// - `Reset`
///
/// When in the `Opening` or `Open` state, the connection can transition to the `Reset` state
/// if the remote closes the connection or refuses the connection altogether. When that
/// happens, [`connection_reset`] must be called. Once in the `Reset` state, the connection
/// cannot transition back to another state.
///
/// Initially in the `Opening` state, the connection can transition to the `Open` state if the
/// remote accepts the connection. When that happens, [`connection_open_single_stream`] or
/// [`connection_open_multi_stream`] must be called.
///
/// There exists two kind of connections: single-stream and multi-stream. Single-stream
/// connections are assumed to have a single stream open at all time and the encryption and
/// multiplexing are handled internally by smoldot. Multi-stream connections open and close
/// streams over time using [`connection_stream_opened`] and [`stream_reset`], and the
/// encryption and multiplexing are handled by the user of these bindings.
#[no_mangle]
pub extern "C" fn connection_new(
id: u32,
addr_ptr: u32,
addr_len: u32,
error_buffer_index_ptr: u32,
) -> u32 {
0
}
/// Abruptly close a connection previously initialized with [`connection_new`].
///
/// This destroys the identifier passed as parameter. This identifier must never be passed
/// through the FFI boundary, unless the same identifier is later allocated again with
/// [`connection_new`].
///
/// Must never be called if [`connection_reset`] has been called on that object in the past.
///
/// The connection must be closed in the background. The Rust code isn't interested in incoming
/// messages from this connection anymore.
///
/// > **Note**: In JavaScript, remember to unregister event handlers before calling for
/// > example `WebSocket.close()`.
#[no_mangle]
pub extern "C" fn reset_connection(id: u32) {}
/// Queues a new outbound substream opening. The [`connection_stream_opened`] function must
/// later be called when the substream has been successfully opened.
///
/// This function will only be called for multi-stream connections. The connection must
/// currently be in the `Open` state. See the documentation of [`connection_new`] for details.
///
/// > **Note**: No mechanism exists in this API to handle the situation where a substream fails
/// > to open, as this is not supposed to happen. If you need to handle such a
/// > situation, either try again opening a substream again or reset the entire
/// > connection.
#[no_mangle]
pub extern "C" fn connection_stream_open(connection_id: u32) {}
/// Abruptly closes an existing substream of a multi-stream connection. The substream must
/// currently be in the `Open` state.
///
/// Must never be called if [`stream_reset`] has been called on that object in the past.
///
/// This function will only be called for multi-stream connections. The connection must
/// currently be in the `Open` state. See the documentation of [`connection_new`] for details.
#[no_mangle]
pub extern "C" fn connection_stream_reset(connection_id: u32, stream_id: u32) {}
/// Queues data on the given stream. The data is found in the memory of the WebAssembly
/// virtual machine, at the given pointer.
///
/// If `connection_id` is a single-stream connection, then the value of `stream_id` should
/// be ignored. If `connection_id` is a multi-stream connection, then the value of `stream_id`
/// contains the identifier of the stream on which to send the data, as was provided to
/// [`connection_stream_opened`].
///
/// The connection associated with that stream (and, in the case of a multi-stream connection,
/// the stream itself must currently be in the `Open` state. See the documentation of
/// [`connection_new`] for details.
///
/// The size of the buffer must not exceed the number of writable bytes of the given stream.
/// Use [`stream_writable_bytes`] to notify that more data can be sent on the stream.
#[no_mangle]
pub extern "C" fn stream_send(connection_id: u32, stream_id: u32, ptr: u32, len: u32) {}
/// Close the sending side of the given stream of the given connection.
///
/// Never called for connection types where this isn't possible to implement (i.e. WebSocket
/// and WebRTC at the moment).
///
/// If `connection_id` is a single-stream connection, then the value of `stream_id` should
/// be ignored. If `connection_id` is a multi-stream connection, then the value of `stream_id`
/// contains the identifier of the stream whose sending side should be closed, as was provided
/// to [`connection_stream_opened`].
///
/// The connection associated with that stream (and, in the case of a multi-stream connection,
/// the stream itself must currently be in the `Open` state. See the documentation of
/// [`connection_new`] for details.
#[no_mangle]
pub extern "C" fn stream_send_close(connection_id: u32, stream_id: u32) {}
/// Called when the Wasm execution enters the context of a certain task. This is useful for
/// debugging purposes.
///
/// Only one task can be currently executing at any time.
///
/// The name of the task is a UTF-8 string found in the memory of the WebAssembly virtual
/// machine at offset `ptr` and with length `len`.
#[no_mangle]
pub extern "C" fn current_task_entered(ptr: u32, len: u32) {}
/// Called when the Wasm execution leave the context of a certain task. This is useful for
/// debugging purposes.
///
/// Only one task can be currently executing at any time.
#[no_mangle]
pub extern "C" fn current_task_exit() {}
/// The LightClient RPC offers a slightly different RPC methods than the
/// substrate based chains. This is because the light client only exposes
@@ -448,7 +195,7 @@ impl LightClient {
// env!("CARGO_PKG_VERSION").into(),
// );
let platform = WasmPlatform::new();
let platform = Platform::new();
let mut client = smoldot_light::Client::new(platform);
@@ -493,14 +240,20 @@ impl LightClient {
// This avoids having to create a separate `HashMap<ChainId, ...>` in parallel of the
// client.
user_data: (),
})
.map_err(|err| LightClientError::AddChainError(err.to_string()))?;
}).expect("OPS");
let (to_backend, backend) = mpsc::channel(128);
// `json_rpc_responses` can only be `None` if we had passed `json_rpc: Disabled`.
let rpc_responses = json_rpc_responses.expect("Light client RPC configured; qed");
#[cfg(not(feature = "unstable-light-client-wasm"))]
tokio::spawn(async move {
let mut task = BackgroundTask::new();
task.start_task(backend, rpc_responses).await;
});
#[cfg(feature = "unstable-light-client-wasm")]
wasm_bindgen_futures::spawn_local(async move {
// tokio::spawn(async move {
let mut task = BackgroundTask::new();
+7
View File
@@ -1,6 +1,13 @@
mod background;
mod client;
#[cfg(feature = "unstable-light-client-wasm")]
mod platform;
#[cfg(feature = "unstable-light-client-wasm")]
mod web_connection;
mod tokio_platform;
pub use client::LightClient;
+567
View File
@@ -0,0 +1,567 @@
use core::time::Duration;
use futures::{prelude::*, task::Poll};
use smoldot::libp2p::{
multiaddr::{Multiaddr, ProtocolRef}
};
#[cfg(not(feature = "unstable-light-client-wasm"))]
use smoldot::libp2p::websocket as smoldot_websocket;
use smoldot_light::platform::{
ConnectError, PlatformConnection, PlatformRef, PlatformSubstreamDirection, ReadBuffer,
};
use std::{
collections::VecDeque,
io::IoSlice,
net::{IpAddr, SocketAddr},
pin::Pin,
};
#[cfg(feature = "unstable-light-client-wasm")]
use super::web_connection::Connection as WebConnection;
#[cfg(feature = "unstable-light-client-wasm")]
use gloo_net::websocket;
#[cfg(feature = "unstable-light-client-wasm")]
use gloo_net::websocket::{futures::WebSocket, Message, State, WebSocketError};
#[cfg(not(feature = "unstable-light-client-wasm"))]
use tokio::net::TcpStream;
#[cfg(not(feature = "unstable-light-client-wasm"))]
use tokio_util::compat::{Compat, TokioAsyncReadCompatExt};
#[cfg(not(feature = "unstable-light-client-wasm"))]
type CompatTcpStream = Compat<TcpStream>;
/// Platform implementation for tokio
/// This implementation is a conversion of the implementation for async-std:
/// https://github.com/smol-dot/smoldot/blob/54d88891b1da202b4bf612a150df7b4dbfa03a55/light-base/src/platform/async_std.rs#L40
#[derive(Clone)]
pub struct TokioPlatform {}
impl TokioPlatform {
pub fn new() -> Self {
TokioPlatform {}
}
}
#[cfg(not(feature = "unstable-light-client-wasm"))]
type Instant = std::time::Instant;
#[cfg(feature = "unstable-light-client-wasm")]
type Instant = instant::Instant;
impl PlatformRef for TokioPlatform {
type Delay = future::BoxFuture<'static, ()>;
type Yield = future::Ready<()>;
#[cfg(not(feature = "unstable-light-client-wasm"))]
type Instant = std::time::Instant;
#[cfg(feature = "unstable-light-client-wasm")]
type Instant = instant::Instant;
type Connection = std::convert::Infallible;
type Stream = Stream;
type ConnectFuture = future::BoxFuture<
'static,
Result<PlatformConnection<Self::Stream, Self::Connection>, ConnectError>,
>;
type StreamUpdateFuture<'a> = future::BoxFuture<'a, ()>;
type NextSubstreamFuture<'a> =
future::Pending<Option<(Self::Stream, PlatformSubstreamDirection)>>;
fn now_from_unix_epoch(&self) -> Duration {
// Intentionally panic if the time is configured earlier than the UNIX EPOCH.
#[cfg(not(feature = "unstable-light-client-wasm"))]
{
std::time::UNIX_EPOCH.elapsed().unwrap()
}
#[cfg(feature = "unstable-light-client-wasm")]
{
instant::SystemTime::now()
.duration_since(instant::SystemTime::UNIX_EPOCH)
.unwrap_or_else(|_| {
panic!("Invalid systime cannot be configured earlier than `UNIX_EPOCH`")
})
}
}
fn now(&self) -> Self::Instant {
#[cfg(not(feature = "unstable-light-client-wasm"))]
{
std::time::Instant::now()
}
#[cfg(feature = "unstable-light-client-wasm")]
{
instant::Instant::now()
}
}
fn sleep(&self, duration: Duration) -> Self::Delay {
#[cfg(not(feature = "unstable-light-client-wasm"))]
{
tokio::time::sleep(duration).boxed()
}
#[cfg(feature = "unstable-light-client-wasm")]
{
futures_timer::Delay::new(duration).boxed()
}
}
fn sleep_until(&self, when: Self::Instant) -> Self::Delay {
self.sleep(when.saturating_duration_since(self.now()))
}
fn yield_after_cpu_intensive(&self) -> Self::Yield {
// No-op.
future::ready(())
}
fn connect(&self, multiaddr: &str) -> Self::ConnectFuture {
// We simply copy the address to own it. We could be more zero-cost here, but doing so
// would considerably complicate the implementation.
let multiaddr = multiaddr.to_owned();
tracing::warn!("Connect called with {:?}", multiaddr);
Box::pin(async move {
let addr = multiaddr.parse::<Multiaddr>().map_err(|_| ConnectError {
is_bad_addr: true,
message: "Failed to parse address".to_string(),
})?;
let mut iter = addr.iter().fuse();
let proto1 = iter.next().ok_or(ConnectError {
is_bad_addr: true,
message: "Unknown protocols combination".to_string(),
})?;
let proto2 = iter.next().ok_or(ConnectError {
is_bad_addr: true,
message: "Unknown protocols combination".to_string(),
})?;
let proto3 = iter.next();
if iter.next().is_some() {
return Err(ConnectError {
is_bad_addr: true,
message: "Unknown protocols combination".to_string(),
});
}
// TODO: doesn't support WebSocket secure connections
// Ensure ahead of time that the multiaddress is supported.
let (addr, host_if_websocket) = match (&proto1, &proto2, &proto3) {
(ProtocolRef::Ip4(ip), ProtocolRef::Tcp(port), None) => (
either::Left(SocketAddr::new(IpAddr::V4((*ip).into()), *port)),
None,
),
(ProtocolRef::Ip6(ip), ProtocolRef::Tcp(port), None) => (
either::Left(SocketAddr::new(IpAddr::V6((*ip).into()), *port)),
None,
),
(ProtocolRef::Ip4(ip), ProtocolRef::Tcp(port), Some(ProtocolRef::Ws)) => {
let addr = SocketAddr::new(IpAddr::V4((*ip).into()), *port);
(either::Left(addr), Some(addr.to_string()))
}
(ProtocolRef::Ip6(ip), ProtocolRef::Tcp(port), Some(ProtocolRef::Ws)) => {
let addr = SocketAddr::new(IpAddr::V6((*ip).into()), *port);
(either::Left(addr), Some(addr.to_string()))
}
// TODO: we don't care about the differences between Dns, Dns4, and Dns6
(
ProtocolRef::Dns(addr) | ProtocolRef::Dns4(addr) | ProtocolRef::Dns6(addr),
ProtocolRef::Tcp(port),
None,
) => (either::Right((addr.to_string(), *port)), None),
(
ProtocolRef::Dns(addr) | ProtocolRef::Dns4(addr) | ProtocolRef::Dns6(addr),
ProtocolRef::Tcp(port),
Some(ProtocolRef::Ws),
) => (
either::Right((addr.to_string(), *port)),
Some(format!("{}:{}", addr, *port)),
),
_ => {
return Err(ConnectError {
is_bad_addr: true,
message: "Unknown protocols combination".to_string(),
})
}
};
tracing::warn!("Connectingto addr: {:?}", addr);
#[cfg(not(feature = "unstable-light-client-wasm"))]
{
use websocket::ClientBuilder;
let addr_2 = "ws://127.0.0.1:30333".to_string();
tracing::warn!("Connecting WebSocket client");
let client = ClientBuilder::new(&addr_2)
.unwrap()
.connect_insecure()
.unwrap();
tracing::warn!("Client connected");
let tcp_socket = match addr {
either::Left(socket_addr) => tokio::net::TcpStream::connect(socket_addr).await,
either::Right((dns, port)) => {
tokio::net::TcpStream::connect((&dns[..], port)).await
}
};
if let Ok(tcp_socket) = &tcp_socket {
let _ = tcp_socket.set_nodelay(true);
}
tracing::warn!("Perform socket handshake");
let socket: TcpOrWs = match (tcp_socket, host_if_websocket) {
(Ok(tcp_socket), Some(host)) => future::Either::Right(
smoldot_websocket::websocket_client_handshake(smoldot_websocket::Config {
tcp_socket: tcp_socket.compat(),
host: &host,
url: "/",
})
.await
.map_err(|err| ConnectError {
message: format!("Failed to negotiate WebSocket: {err}"),
is_bad_addr: false,
})?,
),
(Ok(tcp_socket), None) => future::Either::Left(tcp_socket.compat()),
(Err(err), _) => {
return Err(ConnectError {
is_bad_addr: false,
message: format!("Failed to reach peer: {err}"),
})
}
};
Ok(PlatformConnection::SingleStreamMultistreamSelectNoiseYamux(
Stream {
socket,
buffers: Some((
StreamReadBuffer::Open {
buffer: vec![0; 16384],
cursor: 0..0,
},
StreamWriteBuffer::Open {
buffer: VecDeque::with_capacity(16384),
must_close: false,
must_flush: false,
},
)),
},
))
}
#[cfg(feature = "unstable-light-client-wasm")]
{
use super::web_connection::Connection as WebConnection;
// NOTE: `web_sys::Websocket` has the same behavior:
use web_sys::{MessageEvent, WebSocket as WebSysWebsocket};
// new code to use web_connection:
let addr = "ws://127.0.0.1:30333".to_string();
tracing::warn!("[backend] WASM ATTEMPTING TO CONNECT!");
let mut websocket = match WebSysWebsocket::new(&addr) {
Ok(websocket) => websocket,
Err(err) => {
tracing::warn!("[background] Cannot connect to add {:?}", err);
panic!("OPSS");
// let err = ConnectError {
// is_bad_addr: false,
// message: "Cannot establish WebSocket connection".to_string(),
// };
}
};
let mut websocket = WebConnection::new(websocket);
// // Send the ACK only after the socket is fully opened.
// let mut connected = false;
// for retry in 0..10 {
// let state = websocket.state();
// tracing::trace!("[background] [{}] Websocket state={:?}", retry, state);
// if state.0 {
// connected = true;
// break;
// }
// // futures_timer::Delay::new(Duration::from_secs(2)).await
// }
tracing::warn!("[background] SOCKET FULLY CONNECTED?");
Ok(PlatformConnection::SingleStreamMultistreamSelectNoiseYamux(
Stream {
socket: websocket,
buffers: Some((
StreamReadBuffer::Open {
buffer: vec![0; 16384],
cursor: 0..0,
},
StreamWriteBuffer::Open {
buffer: VecDeque::with_capacity(16384),
must_close: false,
must_flush: false,
},
)),
},
))
}
})
}
fn open_out_substream(&self, c: &mut Self::Connection) {
// This function can only be called with so-called "multi-stream" connections. We never
// open such connection.
match *c {}
}
fn next_substream<'a>(&self, c: &'a mut Self::Connection) -> Self::NextSubstreamFuture<'a> {
// This function can only be called with so-called "multi-stream" connections. We never
// open such connection.
match *c {}
}
fn update_stream<'a>(&self, stream: &'a mut Self::Stream) -> Self::StreamUpdateFuture<'a> {
Box::pin(future::poll_fn(|cx| {
let Some((read_buffer, write_buffer)) = stream.buffers.as_mut() else { return Poll::Pending };
// Whether the future returned by `update_stream` should return `Ready` or `Pending`.
let mut update_stream_future_ready = false;
if let StreamReadBuffer::Open {
buffer: ref mut buf,
ref mut cursor,
} = read_buffer
{
// When reading data from the socket, `poll_read` might return "EOF". In that
// situation, we transition to the `Closed` state, which would discard the data
// currently in the buffer. For this reason, we only try to read if there is no
// data left in the buffer.
if cursor.start == cursor.end {
if let Poll::Ready(result) = Pin::new(&mut stream.socket).poll_read(cx, buf) {
update_stream_future_ready = true;
match result {
Err(_) => {
// End the stream.
stream.buffers = None;
return Poll::Ready(());
}
Ok(0) => {
// EOF.
*read_buffer = StreamReadBuffer::Closed;
}
Ok(bytes) => {
*cursor = 0..bytes;
}
}
}
}
}
if let StreamWriteBuffer::Open {
buffer: ref mut buf,
must_flush,
must_close,
} = write_buffer
{
while !buf.is_empty() {
let write_queue_slices = buf.as_slices();
if let Poll::Ready(result) = Pin::new(&mut stream.socket).poll_write_vectored(
cx,
&[
IoSlice::new(write_queue_slices.0),
IoSlice::new(write_queue_slices.1),
],
) {
if !*must_close {
// In the situation where the API user wants to close the writing
// side, simply sending the buffered data isn't enough to justify
// making the future ready.
update_stream_future_ready = true;
}
match result {
Err(_) => {
// End the stream.
stream.buffers = None;
return Poll::Ready(());
}
Ok(bytes) => {
*must_flush = true;
for _ in 0..bytes {
buf.pop_front();
}
}
}
} else {
break;
}
}
if buf.is_empty() && *must_close {
if let Poll::Ready(result) = Pin::new(&mut stream.socket).poll_close(cx) {
update_stream_future_ready = true;
match result {
Err(_) => {
// End the stream.
stream.buffers = None;
return Poll::Ready(());
}
Ok(()) => {
*write_buffer = StreamWriteBuffer::Closed;
}
}
}
} else if *must_flush {
if let Poll::Ready(result) = Pin::new(&mut stream.socket).poll_flush(cx) {
update_stream_future_ready = true;
match result {
Err(_) => {
// End the stream.
stream.buffers = None;
return Poll::Ready(());
}
Ok(()) => {
*must_flush = false;
}
}
}
}
}
if update_stream_future_ready {
Poll::Ready(())
} else {
Poll::Pending
}
}))
}
fn read_buffer<'a>(&self, stream: &'a mut Self::Stream) -> ReadBuffer<'a> {
match stream.buffers.as_ref().map(|(r, _)| r) {
None => ReadBuffer::Reset,
Some(StreamReadBuffer::Closed) => ReadBuffer::Closed,
Some(StreamReadBuffer::Open { buffer, cursor }) => {
ReadBuffer::Open(&buffer[cursor.clone()])
}
}
}
fn advance_read_cursor(&self, stream: &mut Self::Stream, extra_bytes: usize) {
let Some(StreamReadBuffer::Open { ref mut cursor, .. }) =
stream.buffers.as_mut().map(|(r, _)| r)
else {
assert_eq!(extra_bytes, 0);
return
};
assert!(cursor.start + extra_bytes <= cursor.end);
cursor.start += extra_bytes;
}
fn writable_bytes(&self, stream: &mut Self::Stream) -> usize {
let Some(StreamWriteBuffer::Open { ref mut buffer, must_close: false, ..}) =
stream.buffers.as_mut().map(|(_, w)| w) else { return 0 };
buffer.capacity() - buffer.len()
}
fn send(&self, stream: &mut Self::Stream, data: &[u8]) {
debug_assert!(!data.is_empty());
// Because `writable_bytes` returns 0 if the writing side is closed, and because `data`
// must always have a size inferior or equal to `writable_bytes`, we know for sure that
// the writing side isn't closed.
let Some(StreamWriteBuffer::Open { ref mut buffer, .. } )=
stream.buffers.as_mut().map(|(_, w)| w) else { panic!() };
buffer.reserve(data.len());
buffer.extend(data.iter().copied());
}
fn close_send(&self, stream: &mut Self::Stream) {
// It is not illegal to call this on an already-reset stream.
let Some((_, write_buffer)) = stream.buffers.as_mut() else { return };
match write_buffer {
StreamWriteBuffer::Open {
must_close: must_close @ false,
..
} => *must_close = true,
_ => {
// However, it is illegal to call this on a stream that was already close
// attempted.
panic!()
}
}
}
fn spawn_task(&self, _: std::borrow::Cow<str>, task: future::BoxFuture<'static, ()>) {
#[cfg(not(feature = "unstable-light-client-wasm"))]
tokio::spawn(task);
#[cfg(feature = "unstable-light-client-wasm")]
wasm_bindgen_futures::spawn_local(task);
}
fn client_name(&self) -> std::borrow::Cow<str> {
"cumulus-relay-chain-light-client".into()
}
fn client_version(&self) -> std::borrow::Cow<str> {
env!("CARGO_PKG_VERSION").into()
}
}
/// Implementation detail of [`AsyncStdTcpWebSocket`].
pub struct Stream {
socket: TcpOrWs,
/// Read and write buffers of the connection, or `None` if the socket has been reset.
buffers: Option<(StreamReadBuffer, StreamWriteBuffer)>,
}
enum StreamReadBuffer {
Open {
buffer: Vec<u8>,
cursor: std::ops::Range<usize>,
},
Closed,
}
enum StreamWriteBuffer {
Open {
buffer: VecDeque<u8>,
must_flush: bool,
must_close: bool,
},
Closed,
}
#[cfg(not(feature = "unstable-light-client-wasm"))]
type TcpOrWs = future::Either<CompatTcpStream, smoldot_websocket::Connection<CompatTcpStream>>;
#[cfg(feature = "unstable-light-client-wasm")]
type TcpOrWs = WebConnection;
+201
View File
@@ -0,0 +1,201 @@
#![warn(clippy::all, rust_2018_idioms)]
use futures::{future::Ready, io, prelude::*};
use send_wrapper::SendWrapper;
use smoldot::libp2p::multiaddr::{Multiaddr, ProtocolRef};
use wasm_bindgen::{prelude::*, JsCast};
use web_sys::{MessageEvent, WebSocket};
use std::{
collections::VecDeque,
pin::Pin,
sync::{Arc, Mutex},
task::Poll,
task::{Context, Waker},
};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("js function error {0}")]
JsError(String),
#[error("operation not supported")]
NotSupported,
}
/// A Websocket connection created by the [`WebsocketTransport`].
pub struct Connection {
/// We need to use Mutex as libp2p requires this to be Send.
shared: Arc<Mutex<Shared>>,
}
struct Shared {
opened: bool,
closed: bool,
error: bool,
data: VecDeque<u8>,
waker: Option<Waker>,
socket: SendWrapper<WebSocket>,
closures: Option<SendWrapper<Closures>>,
}
type Closures = (
Closure<dyn FnMut()>,
Closure<dyn FnMut(MessageEvent)>,
Closure<dyn FnMut(web_sys::Event)>,
Closure<dyn FnMut(web_sys::CloseEvent)>,
);
impl Connection {
/// Returns (open, closed)
pub fn state(&self) -> (bool, bool) {
let shared = self.shared.lock().expect("Poised; qed");
(shared.opened, shared.closed)
}
pub fn new(socket: WebSocket) -> Self {
socket.set_binary_type(web_sys::BinaryType::Arraybuffer);
let shared = Arc::new(Mutex::new(Shared {
opened: false,
closed: false,
error: false,
data: VecDeque::with_capacity(1 << 16),
waker: None,
socket: SendWrapper::new(socket.clone()),
closures: None,
}));
let open_callback = Closure::<dyn FnMut()>::new({
let shared = shared.clone();
move || {
let mut locked = shared.lock().expect("Mutex poised; qed");
locked.opened = true;
if let Some(waker) = &locked.waker {
waker.wake_by_ref();
}
}
});
socket.set_onopen(Some(open_callback.as_ref().unchecked_ref()));
let message_callback = Closure::<dyn FnMut(_)>::new({
let shared = shared.clone();
move |e: MessageEvent| {
if let Ok(abuf) = e.data().dyn_into::<js_sys::ArrayBuffer>() {
let mut locked = shared.lock().expect("Mutex poised; qed");
let bytes = js_sys::Uint8Array::new(&abuf).to_vec();
locked.data.extend(bytes.into_iter());
if let Some(waker) = &locked.waker {
waker.wake_by_ref();
}
} else {
panic!("Unexpected data format {:?}", e.data());
}
}
});
socket.set_onmessage(Some(message_callback.as_ref().unchecked_ref()));
let error_callback = Closure::<dyn FnMut(_)>::new({
let shared = shared.clone();
move |_| {
// The error event for error callback doesn't give any information and
// generates error on the browser console we just signal it to the
// stream.
shared.lock().expect("Mutex poised; qed").error = true;
}
});
socket.set_onerror(Some(error_callback.as_ref().unchecked_ref()));
let close_callback = Closure::<dyn FnMut(_)>::new({
let shared = shared.clone();
move |_| {
let mut locked = shared.lock().expect("Mutex poised; qed");
locked.closed = true;
if let Some(waker) = &locked.waker {
waker.wake_by_ref();
}
}
});
socket.set_onclose(Some(close_callback.as_ref().unchecked_ref()));
// Manage closures memory.
let closures = SendWrapper::new((
open_callback,
message_callback,
error_callback,
close_callback,
));
shared.lock().expect("Mutex poised; qed").closures = Some(closures);
Self { shared }
}
}
impl AsyncRead for Connection {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize, io::Error>> {
let mut shared = self.shared.lock().expect("Mutex poised; qed");
shared.waker = Some(cx.waker().clone());
if shared.error {
Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, "Socket error")))
} else if shared.closed {
Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()))
} else if shared.data.is_empty() {
Poll::Pending
} else {
let n = shared.data.len().min(buf.len());
for k in buf.iter_mut().take(n) {
*k = shared.data.pop_front().unwrap();
}
Poll::Ready(Ok(n))
}
}
}
impl AsyncWrite for Connection {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<Result<usize, io::Error>> {
let mut shared = self.shared.lock().expect("Mutex poised; qed");
shared.waker = Some(cx.waker().clone());
if shared.error {
Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, "Socket error")))
} else if shared.closed {
Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()))
} else if !shared.opened {
Poll::Pending
} else {
match shared.socket.send_with_u8_array(buf) {
Ok(()) => Poll::Ready(Ok(buf.len())),
Err(err) => Poll::Ready(Err(io::Error::new(
io::ErrorKind::Other,
format!("Write error: {err:?}"),
))),
}
}
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Ready(Ok(()))
}
fn poll_close(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
Poll::Pending
}
}
impl Drop for Connection {
fn drop(&mut self) {
let shared = self.shared.lock().expect("Mutex poised; qed");
if shared.opened {
let _ = shared.socket.close();
}
}
}
+2 -2
View File
@@ -47,7 +47,7 @@
#[cfg(feature = "jsonrpsee")]
mod jsonrpsee_impl;
#[cfg(feature = "unstable-light-client")]
#[cfg(any(feature = "unstable-light-client", feature = "unstable-light-client-wasm"))]
mod lightclient;
mod rpc;
@@ -66,5 +66,5 @@ pub use rpc_client_t::{
pub use rpc_client::{rpc_params, RpcClient, RpcParams, Subscription};
#[cfg(feature = "unstable-light-client")]
#[cfg(any(feature = "unstable-light-client", feature = "unstable-light-client-wasm"))]
pub use lightclient::{LightClient, LightClientError};
+172 -224
View File
@@ -71,23 +71,9 @@ dependencies = [
[[package]]
name = "arrayvec"
version = "0.7.2"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"
[[package]]
name = "async-executor"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb"
dependencies = [
"async-lock",
"async-task",
"concurrent-queue",
"fastrand",
"futures-lite",
"slab",
]
checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c"
[[package]]
name = "async-lock"
@@ -98,12 +84,6 @@ dependencies = [
"event-listener",
]
[[package]]
name = "async-task"
version = "4.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc7ab41815b3c653ccd2978ec3255c81349336702dfdf62ee6f7069b12a3aae"
[[package]]
name = "async-trait"
version = "0.1.68"
@@ -112,7 +92,7 @@ checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -141,9 +121,9 @@ checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.21.1"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f1e31e207a6b8fb791a38ea3105e6cb541f55e4d029902d3039a4ad07cc4105"
checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d"
[[package]]
name = "beef"
@@ -213,8 +193,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c2f0dc9a68c6317d884f97cc36cf5a3d20ba14ce404227df55e1af708ab04bc"
dependencies = [
"arrayref",
"arrayvec 0.7.2",
"constant_time_eq 0.2.5",
"arrayvec 0.7.3",
"constant_time_eq 0.2.6",
]
[[package]]
@@ -237,9 +217,12 @@ dependencies = [
[[package]]
name = "bs58"
version = "0.4.0"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3"
checksum = "f5353f36341f7451062466f0b755b96ac3a9547e4d7f6b70d603fc721a7d7896"
dependencies = [
"tinyvec",
]
[[package]]
name = "bumpalo"
@@ -311,15 +294,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "concurrent-queue"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62ec6771ecfa0762d24683ee5a32ad78487a3d3afdc0fb8cae19d2c5deb50b7c"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
@@ -338,9 +312,9 @@ checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
[[package]]
name = "constant_time_eq"
version = "0.2.5"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13418e745008f7349ec7e449155f419a61b92b58a99cc3616942b926825ec76b"
checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6"
[[package]]
name = "convert_case"
@@ -366,9 +340,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa"
[[package]]
name = "cpufeatures"
version = "0.2.7"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58"
checksum = "03e69e28e9f7f77debdedbaafa2866e1de9ba56df55a8bd7cfc724c25a09987c"
dependencies = [
"libc",
]
@@ -385,9 +359,9 @@ dependencies = [
[[package]]
name = "crossbeam-utils"
version = "0.8.15"
version = "0.8.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c063cd8cc95f5c377ed0d4b49a4b21f632396ff690e8470c29b3359b346984b"
checksum = "5a22b2d63d4d1dc0b7f1b6b2747dd0088008a9be28b6ddf0b1e7d335e3037294"
dependencies = [
"cfg-if",
]
@@ -512,7 +486,7 @@ dependencies = [
"proc-macro2",
"quote",
"strsim",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -534,7 +508,7 @@ checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a"
dependencies = [
"darling_core 0.20.1",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -613,15 +587,6 @@ version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"
[[package]]
name = "fastrand"
version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e51093e27b0797c359783294ca4f0a911c270184cb10f85783b118614a1501be"
dependencies = [
"instant",
]
[[package]]
name = "fiat-crypto"
version = "0.1.20"
@@ -712,21 +677,6 @@ version = "0.3.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fff74096e71ed47f8e023204cfd0aa1289cd54ae5430a9523be060cdb849964"
[[package]]
name = "futures-lite"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce"
dependencies = [
"fastrand",
"futures-core",
"futures-io",
"memchr",
"parking",
"pin-project-lite",
"waker-fn",
]
[[package]]
name = "futures-macro"
version = "0.3.28"
@@ -735,7 +685,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -757,7 +707,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c"
dependencies = [
"gloo-timers",
"send_wrapper",
"send_wrapper 0.4.0",
]
[[package]]
@@ -790,9 +740,9 @@ dependencies = [
[[package]]
name = "getrandom"
version = "0.2.9"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c85e1d9ab2eadba7e5040d4e09cbd6d072b76a557ad64e797c2cb9d4da21d7e4"
checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
dependencies = [
"cfg-if",
"js-sys",
@@ -886,9 +836,9 @@ dependencies = [
[[package]]
name = "hashbrown"
version = "0.13.2"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43a3c133739dddd0d2990f9a4bdf8eb4b21ef50e4851ca85ab661199821d510e"
checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
dependencies = [
"serde",
]
@@ -1067,8 +1017,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "intx"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f38a50a899dc47a6d0ed5508e7f601a2e34c3a85303514b5d137f3c10a0c75"
[[package]]
name = "itertools"
version = "0.10.5"
@@ -1086,9 +1045,9 @@ checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6"
[[package]]
name = "js-sys"
version = "0.3.63"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f37a4a5928311ac501dee68b3c7613a1037d0edb30c8e5427bd832d55d1b790"
checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"
dependencies = [
"wasm-bindgen",
]
@@ -1204,9 +1163,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.144"
version = "0.2.146"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b00cc1c228a6782d0f076e7b232802e0c5689d41bb5df366f2a6b6621cfdfe1"
checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b"
[[package]]
name = "libm"
@@ -1270,12 +1229,9 @@ dependencies = [
[[package]]
name = "log"
version = "0.4.17"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e"
dependencies = [
"cfg-if",
]
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
[[package]]
name = "lru"
@@ -1309,14 +1265,13 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "mio"
version = "0.8.6"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9"
checksum = "927a765cd3fc26206e66b296465fa9d3e5ab003e651c1b3c060e7956d96b19d2"
dependencies = [
"libc",
"log",
"wasi",
"windows-sys 0.45.0",
"windows-sys 0.48.0",
]
[[package]]
@@ -1385,9 +1340,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.17.1"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "opaque-debug"
@@ -1413,11 +1368,11 @@ dependencies = [
[[package]]
name = "parity-scale-codec"
version = "3.5.0"
version = "3.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ddb756ca205bd108aee3c62c6d3c994e1df84a59b9d6d4a5ea42ee1fd5a9a28"
checksum = "430d26d62e66cbff6ae144e8eebd43c0235922dec7e3aa0d2016c32d4575bf45"
dependencies = [
"arrayvec 0.7.2",
"arrayvec 0.7.3",
"bitvec",
"byte-slice-cast",
"impl-trait-for-tuples",
@@ -1427,9 +1382,9 @@ dependencies = [
[[package]]
name = "parity-scale-codec-derive"
version = "3.1.4"
version = "3.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86b26a931f824dd4eca30b3e43bb4f31cd5f0d3a403c5f5ff27106b805bfde7b"
checksum = "a1620b1e3fc72ebaee01ff56fca838bab537c5d093a18b3549c3bbea374aa0b6"
dependencies = [
"proc-macro-crate",
"proc-macro2",
@@ -1437,12 +1392,6 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "parking"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"
[[package]]
name = "paste"
version = "1.0.12"
@@ -1475,7 +1424,7 @@ checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -1574,9 +1523,9 @@ dependencies = [
[[package]]
name = "proc-macro2"
version = "1.0.59"
version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6aeca18b86b413c660b781aa319e4e2648a3e6f9eadc9b47e9038e6fe9f3451b"
checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406"
dependencies = [
"unicode-ident",
]
@@ -1682,9 +1631,9 @@ dependencies = [
[[package]]
name = "rustls-native-certs"
version = "0.6.2"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0167bac7a9f490495f3c33013e7722b53cb087ecbe082fb0c6387c96f634ea50"
checksum = "a9aace74cb666635c918e9c12bc0d348266037aa8eb599b5cba565709a8dff00"
dependencies = [
"openssl-probe",
"rustls-pemfile",
@@ -1698,17 +1647,17 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b"
dependencies = [
"base64 0.21.1",
"base64 0.21.2",
]
[[package]]
name = "ruzstd"
version = "0.3.1"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a15e661f0f9dac21f3494fe5d23a6338c0ac116a2d22c2b63010acd89467ffe"
checksum = "ac3ffab8f9715a0d455df4bbb9d21e91135aab3cd3ca187af0cd0c3c3f868fdc"
dependencies = [
"byteorder",
"thiserror",
"thiserror-core",
"twox-hash",
]
@@ -1843,7 +1792,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "844b7645371e6ecdf61ff246ba1958c29e802881a749ae3fb1993675d210d28d"
dependencies = [
"arrayref",
"arrayvec 0.7.2",
"arrayvec 0.7.3",
"curve25519-dalek-ng",
"merlin",
"rand_core 0.6.4",
@@ -1904,30 +1853,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f638d531eccd6e23b980caf34876660d38e265409d8e99b397ab71eb3612fad0"
[[package]]
name = "serde"
version = "1.0.163"
name = "send_wrapper"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2113ab51b87a539ae008b5c6c02dc020ffa39afd2d83cffcb3f4eb2722cebec2"
checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73"
[[package]]
name = "serde"
version = "1.0.164"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.163"
version = "1.0.164"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8c805777e3930c8883389c602315a24224bcc738b63905ef87cd1420353ea93e"
checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
name = "serde_json"
version = "1.0.96"
version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1"
checksum = "bdf3bf93142acad5821c99197022e170842cdbc1c30482b98750c688c640842a"
dependencies = [
"itoa",
"ryu",
@@ -1962,9 +1917,9 @@ dependencies = [
[[package]]
name = "sha2"
version = "0.10.6"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0"
checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8"
dependencies = [
"cfg-if",
"cpufeatures",
@@ -2013,12 +1968,13 @@ checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"
[[package]]
name = "smoldot"
version = "0.6.0"
version = "0.7.0"
source = "git+https://github.com/smol-dot/smoldot?rev=cf211107#cf21110789140f42f9f21880c1517ef086cc3e2e"
dependencies = [
"arrayvec 0.7.2",
"arrayvec 0.7.3",
"async-lock",
"atomic",
"base64 0.21.1",
"base64 0.21.2",
"bip39",
"blake2-rfc",
"bs58",
@@ -2030,7 +1986,7 @@ dependencies = [
"fnv",
"futures-channel",
"futures-util",
"hashbrown 0.13.2",
"hashbrown 0.14.0",
"hex",
"hmac 0.12.1",
"itertools",
@@ -2041,7 +1997,6 @@ dependencies = [
"num-bigint",
"num-rational",
"num-traits",
"parity-scale-codec",
"pbkdf2",
"rand",
"rand_chacha",
@@ -2049,7 +2004,7 @@ dependencies = [
"schnorrkel",
"serde",
"serde_json",
"sha2 0.10.6",
"sha2 0.10.7",
"siphasher",
"slab",
"smallvec",
@@ -2061,7 +2016,8 @@ dependencies = [
[[package]]
name = "smoldot-light"
version = "0.4.0"
version = "0.5.0"
source = "git+https://github.com/smol-dot/smoldot?rev=cf211107#cf21110789140f42f9f21880c1517ef086cc3e2e"
dependencies = [
"async-lock",
"blake2-rfc",
@@ -2071,7 +2027,7 @@ dependencies = [
"fnv",
"futures-channel",
"futures-util",
"hashbrown 0.13.2",
"hashbrown 0.14.0",
"hex",
"itertools",
"log",
@@ -2079,30 +2035,11 @@ dependencies = [
"rand",
"serde",
"serde_json",
"siphasher",
"slab",
"smoldot",
]
[[package]]
name = "smoldot-light-wasm"
version = "1.0.6"
dependencies = [
"async-executor",
"async-task",
"event-listener",
"fnv",
"futures-util",
"hashbrown 0.13.2",
"lazy_static",
"log",
"nom",
"pin-project",
"rand",
"slab",
"smoldot",
"smoldot-light",
]
[[package]]
name = "snow"
version = "0.9.2"
@@ -2115,7 +2052,7 @@ dependencies = [
"curve25519-dalek 4.0.0-rc.1",
"rand_core 0.6.4",
"rustc_version",
"sha2 0.10.6",
"sha2 0.10.7",
"subtle",
]
@@ -2153,7 +2090,7 @@ dependencies = [
"blake2b_simd",
"byteorder",
"digest 0.10.7",
"sha2 0.10.6",
"sha2 0.10.7",
"sha3",
"sp-std",
"twox-hash",
@@ -2217,6 +2154,8 @@ dependencies = [
"gloo-net",
"hex",
"impl-serde",
"instant",
"js-sys",
"jsonrpsee",
"parity-scale-codec",
"primitive-types",
@@ -2225,11 +2164,11 @@ dependencies = [
"scale-encode",
"scale-info",
"scale-value",
"send_wrapper 0.6.0",
"serde",
"serde_json",
"smoldot",
"smoldot-light",
"smoldot-light-wasm",
"sp-core-hashing",
"subxt-macro",
"subxt-metadata",
@@ -2237,7 +2176,9 @@ dependencies = [
"tokio",
"tokio-stream",
"tracing",
"wasm-bindgen",
"wasm-bindgen-futures",
"web-sys",
]
[[package]]
@@ -2253,7 +2194,7 @@ dependencies = [
"quote",
"scale-info",
"subxt-metadata",
"syn 2.0.16",
"syn 2.0.18",
"thiserror",
"tokio",
]
@@ -2265,7 +2206,7 @@ dependencies = [
"darling 0.20.1",
"proc-macro-error",
"subxt-codegen",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -2292,9 +2233,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.16"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6f671d4b5ffdb8eadec19c0ae67fe2639df8684bd7bc4b83d986b8db549cf01"
checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
dependencies = [
"proc-macro2",
"quote",
@@ -2316,6 +2257,26 @@ dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-core"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d97345f6437bb2004cd58819d8a9ef8e36cdd7661c2abc4bbde0a7c40d9f497"
dependencies = [
"thiserror-core-impl",
]
[[package]]
name = "thiserror-core-impl"
version = "1.0.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "thiserror-impl"
version = "1.0.40"
@@ -2324,7 +2285,7 @@ checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -2347,10 +2308,25 @@ dependencies = [
]
[[package]]
name = "tokio"
version = "1.28.1"
name = "tinyvec"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0aa32867d44e6f2ce3385e89dceb990188b8bb0fb25b0cf576647a6f98ac5105"
checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.28.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2"
dependencies = [
"autocfg",
"bytes",
@@ -2370,7 +2346,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -2453,7 +2429,7 @@ checksum = "0f57e3ca2a01450b1a921183a9c9cbfda207fd822cef4ccb00a65402cbba7a74"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
[[package]]
@@ -2525,9 +2501,9 @@ dependencies = [
[[package]]
name = "unicode-ident"
version = "1.0.8"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5464a87b239f13a63a501f2701565754bae92d243d4bb7eb12f6d57d2269bf4"
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
[[package]]
name = "universal-hash"
@@ -2551,19 +2527,12 @@ version = "0.9.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
name = "waker-fn"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"
[[package]]
name = "want"
version = "0.3.0"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0"
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
dependencies = [
"log",
"try-lock",
]
@@ -2575,9 +2544,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.86"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bba0e8cb82ba49ff4e229459ff22a191bbe9a1cb3a341610c9c33efc27ddf73"
checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
@@ -2585,24 +2554,24 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.86"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b04bc93f9d6bdee709f6bd2118f57dd6679cf1176a1af464fca3ab0d66d8fb"
checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.36"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d1985d03709c53167ce907ff394f5316aa22cb4e12761295c5dc57dacb6297e"
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
dependencies = [
"cfg-if",
"js-sys",
@@ -2612,9 +2581,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.86"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "14d6b024f1a526bb0234f52840389927257beb670610081360e5a03c5df9c258"
checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@@ -2622,28 +2591,28 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.86"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e128beba882dd1eb6200e1dc92ae6c5dbaa4311aa7bb211ca035779e5efc39f8"
checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.86"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed9d5b4305409d1fc9482fee2d7f9bcbf24b3972bf59817ef757e23982242a93"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
[[package]]
name = "wasm-bindgen-test"
version = "0.3.36"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c9e636f3a428ff62b3742ebc3c70e254dfe12b8c2b469d688ea59cdd4abcf502"
checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671"
dependencies = [
"console_error_panic_hook",
"js-sys",
@@ -2655,9 +2624,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.36"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f18c1fad2f7c4958e7bcce014fa212f59a65d5e3721d0f77e6c0b27ede936ba3"
checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575"
dependencies = [
"proc-macro2",
"quote",
@@ -2668,18 +2637,21 @@ name = "wasm-test"
version = "0.1.0"
dependencies = [
"console_error_panic_hook",
"futures-util",
"serde_json",
"subxt",
"tracing",
"tracing-wasm",
"wasm-bindgen-test",
]
[[package]]
name = "wasmi"
version = "0.29.0"
version = "0.30.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677160b1166881badada1137afc6457777126f328ae63a18058b504f546f0828"
checksum = "e51fb5c61993e71158abf5bb863df2674ca3ec39ed6471c64f07aeaf751d67b4"
dependencies = [
"intx",
"smallvec",
"spin 0.9.8",
"wasmi_arena",
@@ -2716,9 +2688,9 @@ dependencies = [
[[package]]
name = "web-sys"
version = "0.3.63"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bdd9ef4e984da1187bf8110c5cf5b845fbc87a23602cdf912386a76fcd3a7c2"
checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"
dependencies = [
"js-sys",
"wasm-bindgen",
@@ -2780,37 +2752,13 @@ dependencies = [
"windows_x86_64_msvc 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
dependencies = [
"windows-targets 0.42.2",
]
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets 0.48.0",
]
[[package]]
name = "windows-targets"
version = "0.42.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
dependencies = [
"windows_aarch64_gnullvm 0.42.2",
"windows_aarch64_msvc 0.42.2",
"windows_i686_gnu 0.42.2",
"windows_i686_msvc 0.42.2",
"windows_x86_64_gnu 0.42.2",
"windows_x86_64_gnullvm 0.42.2",
"windows_x86_64_msvc 0.42.2",
"windows-targets",
]
[[package]]
@@ -2914,9 +2862,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"
[[package]]
name = "winnow"
version = "0.4.6"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61de7bac303dc551fe038e2b3cef0f571087a47571ea6e79a87692ac99b99699"
checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448"
dependencies = [
"memchr",
]
@@ -2953,5 +2901,5 @@ checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.16",
"syn 2.0.18",
]
+4 -1
View File
@@ -10,9 +10,12 @@ publish = false
# subxt to work. So, we can't inherit versions.
wasm-bindgen-test = "0.3.24"
tracing-wasm = "0.2.1"
tracing = "0.1.34"
console_error_panic_hook = "0.1.7"
serde_json = "1"
subxt = { path = "../../subxt", default-features = false, features = ["jsonrpsee-web", "unstable-light-client"] }
subxt = { path = "../../subxt", default-features = false, features = ["jsonrpsee-web", "unstable-light-client-wasm"] }
futures-util = "0.3.28"
[profile.release]
debug = true
+47 -2
View File
@@ -5,6 +5,11 @@ use subxt::rpc::LightClient;
use wasm_bindgen_test::*;
use std::sync::Arc;
use subxt::rpc::Subscription;
use subxt::rpc::RpcClientT;
use subxt::OnlineClient;
use futures_util::StreamExt;
wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser);
/// Run the tests by `$ wasm-pack test --firefox --headless`
@@ -28,8 +33,48 @@ async fn wasm_ws_transport_works() {
async fn light_client_transport_works() {
init_tracing();
// let light_client = LightClient::new(include_str!("../../../artifacts/dev_spec.json")).unwrap();
// let client = subxt::client::OnlineClient::<PolkadotConfig>::from_rpc_client(Arc::new(light_client)).await.unwrap();
let light_client = LightClient::new(include_str!("../../../artifacts/dev_spec.json")).unwrap();
let api = OnlineClient::<PolkadotConfig>::from_rpc_client(Arc::new(light_client)).await.unwrap();
// Subscribe to the latest 3 finalized blocks.
{
tracing::info!("Subscribe to latest finalized blocks: ");
let mut blocks_sub = api.blocks().subscribe_finalized().await.expect("Cannot subscribe to finalized hashes").take(3);
// For each block, print a bunch of information about it:
while let Some(block) = blocks_sub.next().await {
let block = block.expect("Block not valid");
let block_number = block.header().number;
let block_hash = block.hash();
tracing::info!("Block #{block_number}:");
tracing::info!(" Hash: {block_hash}");
}
}
// Ensure light-client functions with subscriptions.
// let sub = light_client
// .subscribe_raw("chain_subscribeAllHeads", None, "chain_unsubscribeAllHeads")
// .await
// .unwrap();
// The subscription result is actually a PolkadotConfig::Header, we are interested in iteration.
// let mut sub: Subscription<String> = Subscription::new(sub);
// let block = sub
// .next()
// .await
// .expect("Subscription failed")
// .expect("Subscription ended");
// tracing::warn!("Block hash {:?}", block);
// let block = sub
// .next()
// .await
// .expect("Subscription failed")
// .expect("Subscription ended");
// tracing::warn!("Block hash {:?}", block);
// let chain = client.rpc().system_chain().await.unwrap();
// assert_eq!(&chain, "Development");