B-encoding using Python.md
1 See also: [[Using Python on macOS]]. 2 3 We will use a very simple Python script to validate encodings. You can find the script here: https://gist.github.com/marcinczenko/a87baf506bb0fd4bdff752cda4c685a1 4 5 Our input will be the following `data1M.bin.torrent.json` file: 6 7 ```nim 8 { 9 "info": { 10 "length": 1048576, 11 "name": "data1M.bin", 12 "piece length": 262144, 13 "pieces": [ 14 "111421FEBA308CD51E9ACF88417193A9EA60F0F84646", 15 "11143D4A8279853DA2DA355A574740217D446506E8EB", 16 "11141AD686B48B9560B15B8843FD00E7EC1B59624B09", 17 "11145015E7DA0C40350624C6B5A1FED1DB39720B726C" 18 ] 19 } 20 } 21 ``` 22 23 To *b-encode* we run: 24 25 ```bash 26 python bencoder.py --info-only data1M.bin.torrent.json 27 Using values from file: data1M.bin.torrent.json 28 Info only: True 29 { 30 "length": 1048576, 31 "name": "data1M.bin", 32 "piece length": 262144, 33 "pieces": [ 34 "21FEBA308CD51E9ACF88417193A9EA60F0F84646", 35 "3D4A8279853DA2DA355A574740217D446506E8EB", 36 "1AD686B48B9560B15B8843FD00E7EC1B59624B09", 37 "5015E7DA0C40350624C6B5A1FED1DB39720B726C" 38 ] 39 } 40 infohash f335440998515770adf47e8a4626889e59d91dde 41 ``` 42 43 The `--info-only` option instructs the script to only b-encode the info dictionary and do not include other attributes like `announce`. 44 45 We get as an output the `data1M.bin.torrent` file with the following content: 46 47 ```bash 48 d4:infod6:lengthi1048576e4:name10:data1M.bin12:piece lengthi262144e6:pieces80:!��0���ψAq���`��FF=J�y�=��5ZWG@!}De��ֆ���`�[�C� ��YbK P��@5$Ƶ����9rrlee 49 ``` 50 51 It is not very readable, because pieces has been converted to hex strings to a flattened byte array - in the end this is supposed to be machine readable code.