# Receiving all zeroes for the file in stage ND2

**URL:** <https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550>\
**Category:** Challenges\
**Tags:** challenge:bittorrent\
**Created:** [March 25, 2025, 4:31am UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550 "2025-03-25T04:31:01Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![abhishek-7901](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/abhishek-7901/32/6674_2.png) [@abhishek-7901](https://forum.codecrafters.io/u/abhishek-7901)\
**Post date:** [March 25, 2025, 4:31am UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/1 "2025-03-25T04:31:01Z")

</div>

I’m stuck on Stage #ND2.

I am getting all zeroes as output from the peer and the hash is not matching

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/2X/d/d278fc2ab273530e09cc3fd499405e054af6103d.png)

And here’s a snippet of my code:

```javascript
waitForRequestedPiece(client) {
        return new Promise((resolve, reject) => {
            client.on("data", onData)
            client.on("error", onError)

            let buffer = Buffer.alloc(0)
            function onData(chunk) {
                buffer = Buffer.concat([buffer, chunk])

                while (buffer.length >= 4) {
                    const msgLength = buffer.readInt32BE(0)

                    if (msgLength === 0) {
                        console.log("Got keep alive ;)")
                        buffer = buffer.subarray(4)
                        continue
                    }

                    if (buffer.length < msgLength + 4) {
                        console.log("waiting for data")
                        return
                    }

                    const msg = buffer.subarray(4, 4 + msgLength)
                    buffer = buffer.subarray(4 + msgLength)

                    const msgId = msg.readUInt8(0)

                    if (msgId === 7){
                        console.log(`Received piece index`) 

                        const pieceIndex = msg.readInt32BE(1)
                        const begin = msg.readInt32BE(5)
                        const blockData = msg.readInt32BE(9)
                        cleanup()
                        return resolve({pieceIndex, begin, blockData})
                    }
                    else {
                        console.log(`Got msg ID ${msgId}, ignoring...`)
                    }
                }
            }

            function onError(err) {
                cleanup()
                return reject(err)
            }

            function cleanup() {
                client.removeListener("data", onData)
                client.removeListener("error", onError)
            }
        });
    }

async downloadPieces(pieceIndex, outFile) {
        const peers = await this.torrent.getPeers()
        const {client, response} = await this.initiateHandShake(peers[0]);
        try {
            this.sendInterested(client)
            await this.waitForUnchoke(client);
            const pieceLength = this.torrent.getPieceLength()
            const fileLength = this.torrent.getFileLength()
    
            
            const indexPieceLength = (pieceIndex === Math.floor(fileLength/pieceLength)) ? fileLength % pieceLength : pieceLength ;    
            
            const piece = Buffer.alloc(indexPieceLength)
    
            const sixteenKb = 16 * 1024
            let offset = 0;
            while (offset < indexPieceLength) {
                const requestedBlocks = []
                for (let count = 0; count < 5 && offset < indexPieceLength ; count++){
                    const length = Math.min(sixteenKb, indexPieceLength - offset)
                    this.sendPieceRequest(pieceIndex, offset, length, client)
                    requestedBlocks.push(this.waitForRequestedPiece(client))
                    offset += sixteenKb
                }
                const responses = await Promise.all(requestedBlocks)
                for (const {pieceIndex, offset, blockData} of responses){
                    piece[offset] = blockData
                }
            }
    
            const pieceHashes = this.torrent.getPieces()
            const hash = pieceHashes.slice(pieceIndex * 40, pieceIndex * 40 + 40)
            const recievedHash = crypto
                                .createHash("sha1")
                                .update(piece)
                                .digest("hex")
            if (recievedHash !== hash) {
                throw new Error('Piece Hash mismatch')
            }

            fs.writeFileSync(outFile, piece)
        }
        finally {
            client.end()
            client.destroy()
        }

        // console.log(piece.toString("hex"))
    }

```

---

<div class="post-metadata">

**Author:** ![andy1li](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/andy1li/32/10_2.png) [@andy1li](https://forum.codecrafters.io/u/andy1li)\
**Post date:** [March 25, 2025, 4:27pm UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/4 "2025-03-25T16:27:54Z")

</div>

Hey @abhishek-7901, could you push the latest version of your code to our server? Right now, I can only see your submission from over a week ago. Let me know once it’s up!

---

<div class="post-metadata">

**Author:** ![abhishek-7901](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/abhishek-7901/32/6674_2.png) [@abhishek-7901](https://forum.codecrafters.io/u/abhishek-7901)\
**Post date:** [March 26, 2025, 5:04am UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/5 "2025-03-26T05:04:01Z")

</div>

Yes, done, please have a look 🙂

---

<div class="post-metadata">

**Author:** ![andy1li](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/andy1li/32/10_2.png) [@andy1li](https://forum.codecrafters.io/u/andy1li)\
**Post date:** [March 26, 2025, 11:35am UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/6 "2025-03-26T11:35:59Z")

</div>

@abhishek-7901 There could be multiple issues at play. First, the received chunks don’t match the assumed size (`16k + overhead`):

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/2X/c/c45d70824b09847c83ee519d193f5bdd1039a484.jpeg)

Also, I wasn’t quite sure about the arbitrary 5 here:

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/2X/b/b048e2a8699d03a1ddaeacbb802e3b1072c9fde7.png)

I tried changing it to 1 and reran the test:

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/2X/b/be037855c77eb6f8d85fa4366a54a9d9a3b07f69.png)

 ![image](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/2X/8/8cb1ae9bb169d95e0fef137db99335d0aa69272a.jpeg)

Now, most chunks were around 16k, but in some cases, a block could still arrive in two or three chunks.

You’ll need to be able to handle partial chunks and reassemble the full block before processing it.

---

<div class="post-metadata">

**Author:** ![andy1li](https://yyz1.discourse-cdn.com/flex003/user_avatar/forum.codecrafters.io/andy1li/32/10_2.png) [@andy1li](https://forum.codecrafters.io/u/andy1li)\
**Post date:** [April 6, 2025, 4:16pm UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/8 "2025-04-06T16:16:41Z")

</div>

Closing this thread due to inactivity. If you still need assistance, feel free to reopen or start a new discussion!

---

<div class="post-metadata">

**Author:** ![system](https://canada1.discourse-cdn.com/flex003/uploads/codecrafters/original/3X/7/0/700657133935c15703e22c7c8870394f6e6dc27d.svg) [@system](https://forum.codecrafters.io/u/system)\
**Post date:** [April 11, 2025, 4:17pm UTC](https://forum.codecrafters.io/t/receiving-all-zeroes-for-the-file-in-stage-nd2/7550/9 "2025-04-11T16:17:02Z")

</div>

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.
