renter_test.go 132 KB
Newer Older
1
package renter
2 3

import (
4
	"encoding/hex"
Christopher Schinnerl's avatar
Christopher Schinnerl committed
5
	"encoding/json"
6
	"fmt"
7
	"io"
8
	"io/ioutil"
9
	"math"
10
	"math/big"
11
	"os"
12
	"path/filepath"
13
	"reflect"
14
	"sort"
15
	"strconv"
16
	"sync"
17
	"testing"
18
	"time"
19

20 21 22 23
	"gitlab.com/NebulousLabs/Sia/build"
	"gitlab.com/NebulousLabs/Sia/crypto"
	"gitlab.com/NebulousLabs/Sia/modules"
	"gitlab.com/NebulousLabs/Sia/modules/renter"
24
	"gitlab.com/NebulousLabs/Sia/modules/renter/proto"
25
	"gitlab.com/NebulousLabs/Sia/modules/renter/siafile"
26 27 28 29 30
	"gitlab.com/NebulousLabs/Sia/node"
	"gitlab.com/NebulousLabs/Sia/node/api"
	"gitlab.com/NebulousLabs/Sia/node/api/client"
	"gitlab.com/NebulousLabs/Sia/siatest"
	"gitlab.com/NebulousLabs/Sia/types"
31

32 33
	"gitlab.com/NebulousLabs/errors"
	"gitlab.com/NebulousLabs/fastrand"
34 35
)

36 37
// test is a helper struct for running subtests when tests can use the same test
// group
38 39 40 41 42
type test struct {
	name string
	test func(*testing.T, *siatest.TestGroup)
}

43 44
// runRenterTests is a helper function to run the subtests when tests can use
// the same test group
45
func runRenterTests(t *testing.T, gp siatest.GroupParams, tests []test) error {
46
	tg, err := siatest.NewGroupFromTemplate(renterTestDir(t.Name()), gp)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
	if err != nil {
		return errors.AddContext(err, "failed to create group")
	}
	defer func() {
		if err := tg.Close(); err != nil {
			t.Fatal(err)
		}
	}()
	// Run subtests
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			test.test(t, tg)
		})
	}
	return nil
}

64
// TestRenter executes a number of subtests using the same TestGroup to
65
// save time on initialization
66
func TestRenter(t *testing.T) {
67 68 69
	if testing.Short() {
		t.SkipNow()
	}
70
	t.Parallel()
71 72 73 74 75 76 77

	// Create a group for the subtests
	groupParams := siatest.GroupParams{
		Hosts:   5,
		Renters: 1,
		Miners:  1,
	}
78

Thomas Bennett's avatar
Thomas Bennett committed
79
	// Specify subtests to run
80
	subTests := []test{
81 82
		{"TestDownloadMultipleLargeSectors", testDownloadMultipleLargeSectors},
		{"TestLocalRepair", testLocalRepair},
83
		{"TestClearDownloadHistory", testClearDownloadHistory},
84
		{"TestSetFileTrackingPath", testSetFileTrackingPath},
85
		{"TestDownloadAfterRenew", testDownloadAfterRenew},
86
		{"TestDirectories", testDirectories},
87
	}
88 89 90 91

	// Run tests
	if err := runRenterTests(t, groupParams, subTests); err != nil {
		t.Fatal(err)
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
	}
}

// TestRenterTwo executes a number of subtests using the same TestGroup to
// save time on initialization
func TestRenterTwo(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
	t.Parallel()

	// Create a group for the subtests
	groupParams := siatest.GroupParams{
		Hosts:   5,
		Renters: 1,
		Miners:  1,
	}

	// Specify subtests to run
111
	subTests := []test{
Christopher Schinnerl's avatar
Christopher Schinnerl committed
112
		{"TestReceivedFieldEqualsFileSize", testReceivedFieldEqualsFileSize},
113
		{"TestRemoteRepair", testRemoteRepair},
114
		{"TestSingleFileGet", testSingleFileGet},
115
		{"TestStreamingCache", testStreamingCache},
116
		{"TestSiaFileTimestamps", testSiafileTimestamps},
117
		{"TestZeroByteFile", testZeroByteFile},
Drexel's avatar
Drexel committed
118
		{"TestUploadWithAndWithoutForceParameter", testUploadWithAndWithoutForceParameter},
119
		{"TestUploadDownload", testUploadDownload}, // Needs to be last as it impacts hosts
120
	}
121 122 123 124

	// Run tests
	if err := runRenterTests(t, groupParams, subTests); err != nil {
		t.Fatal(err)
125 126 127
	}
}

128 129 130 131 132 133 134 135 136 137
// testSiafileTimestamps tests if timestamps are set correctly when creating,
// uploading, downloading and modifying a file.
func testSiafileTimestamps(t *testing.T, tg *siatest.TestGroup) {
	// Grab the renter.
	r := tg.Renters()[0]

	// Get the current time.
	beforeUploadTime := time.Now()

	// Upload a new file.
138
	_, rf, err := r.UploadNewFileBlocking(100+siatest.Fuzz(), 1, 1, false)
139 140 141 142 143 144 145 146
	if err != nil {
		t.Fatal(err)
	}

	// Get the time again.
	afterUploadTime := time.Now()

	// Get the timestamps using the API.
147
	fi, err := r.File(rf)
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
	if err != nil {
		t.Fatal(err)
	}

	// The timestamps should all be between beforeUploadTime and
	// afterUploadTime.
	if fi.CreateTime.Before(beforeUploadTime) || fi.CreateTime.After(afterUploadTime) {
		t.Fatal("CreateTime was not within the correct interval")
	}
	if fi.AccessTime.Before(beforeUploadTime) || fi.AccessTime.After(afterUploadTime) {
		t.Fatal("AccessTime was not within the correct interval")
	}
	if fi.ChangeTime.Before(beforeUploadTime) || fi.ChangeTime.After(afterUploadTime) {
		t.Fatal("ChangeTime was not within the correct interval")
	}
	if fi.ModTime.Before(beforeUploadTime) || fi.ModTime.After(afterUploadTime) {
		t.Fatal("ModTime was not within the correct interval")
	}

	// After uploading a file the AccessTime, ChangeTime and ModTime should be
	// the same.
	if fi.AccessTime != fi.ChangeTime || fi.ChangeTime != fi.ModTime {
		t.Fatal("AccessTime, ChangeTime and ModTime are not the same")
	}

173
	// The CreateTime should precede the other timestamps.
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	if fi.CreateTime.After(fi.AccessTime) {
		t.Fatal("CreateTime should before other timestamps")
	}

	// Get the time before starting the download.
	beforeDownloadTime := time.Now()

	// Download the file.
	_, err = r.DownloadByStream(rf)
	if err != nil {
		t.Fatal(err)
	}

	// Get the time after the download is done.
	afterDownloadTime := time.Now()

	// Get the timestamps using the API.
191
	fi2, err := r.File(rf)
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
	if err != nil {
		t.Fatal(err)
	}

	// Only the AccessTime should have changed.
	if fi2.AccessTime.Before(beforeDownloadTime) || fi2.AccessTime.After(afterDownloadTime) {
		t.Fatal("AccessTime was not within the correct interval")
	}
	if fi.CreateTime != fi2.CreateTime {
		t.Fatal("CreateTime changed after download")
	}
	if fi.ChangeTime != fi2.ChangeTime {
		t.Fatal("ChangeTime changed after download")
	}
	if fi.ModTime != fi2.ModTime {
		t.Fatal("ModTime changed after download")
	}

	// TODO Once we can change the localPath using the API, check that it only
	// changes the ChangeTime to do so.

	// Get the time before renaming.
	beforeRenameTime := time.Now()

	// Rename the file and check that only the ChangeTime changed.
	rf, err = r.Rename(rf, "newsiapath")
	if err != nil {
		t.Fatal(err)
	}

	// Get the time after renaming.
	afterRenameTime := time.Now()

	// Get the timestamps using the API.
226
	fi3, err := r.File(rf)
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	if err != nil {
		t.Fatal(err)
	}

	// Only the ChangeTime should have changed.
	if fi3.ChangeTime.Before(beforeRenameTime) || fi3.ChangeTime.After(afterRenameTime) {
		t.Fatal("ChangeTime was not within the correct interval")
	}
	if fi2.CreateTime != fi3.CreateTime {
		t.Fatal("CreateTime changed after download")
	}
	if fi2.AccessTime != fi3.AccessTime {
		t.Fatal("AccessTime changed after download")
	}
	if fi2.ModTime != fi3.ModTime {
		t.Fatal("ModTime changed after download")
	}
}

Christopher Schinnerl's avatar
Christopher Schinnerl committed
246 247 248 249 250 251
// TestRenterThree executes a number of subtests using the same TestGroup to
// save time on initialization
func TestRenterThree(t *testing.T) {
	if testing.Short() {
		t.SkipNow()
	}
252
	t.Parallel()
Christopher Schinnerl's avatar
Christopher Schinnerl committed
253 254 255 256 257 258 259 260 261 262 263

	// Create a group for the subtests
	groupParams := siatest.GroupParams{
		Hosts:   5,
		Renters: 1,
		Miners:  1,
	}

	// Specify subtests to run
	subTests := []test{
		{"TestAllowanceDefaultSet", testAllowanceDefaultSet},
264
		{"TestStreamLargeFile", testStreamLargeFile},
Christopher Schinnerl's avatar
Christopher Schinnerl committed
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	}

	// Run tests
	if err := runRenterTests(t, groupParams, subTests); err != nil {
		t.Fatal(err)
	}
}

// testAllowanceDefaultSet tests that a renter's allowance is correctly set to
// the defaults after creating it and therefore confirming that the API
// endpoint and siatest package both work.
func testAllowanceDefaultSet(t *testing.T, tg *siatest.TestGroup) {
	if len(tg.Renters()) == 0 {
		t.Fatal("Test requires at least 1 renter")
	}
	// Get allowance.
	r := tg.Renters()[0]
	rg, err := r.RenterGet()
	if err != nil {
		t.Fatal(err)
	}
	// Make sure that the allowance was set correctly.
	if !reflect.DeepEqual(rg.Settings.Allowance, siatest.DefaultAllowance) {
		expected, _ := json.Marshal(siatest.DefaultAllowance)
		was, _ := json.Marshal(rg.Settings.Allowance)
		t.Log("Expected", string(expected))
		t.Log("Was", string(was))
		t.Fatal("Renter's allowance doesn't match siatest.DefaultAllowance")
	}
}

Christopher Schinnerl's avatar
Christopher Schinnerl committed
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
// testReceivedFieldEqualsFileSize tests that the bug that caused finished
// downloads to stall in the UI and siac is gone.
func testReceivedFieldEqualsFileSize(t *testing.T, tg *siatest.TestGroup) {
	// Make sure the test has enough hosts.
	if len(tg.Hosts()) < 4 {
		t.Fatal("testReceivedFieldEqualsFileSize requires at least 4 hosts")
	}
	// Grab the first of the group's renters
	r := tg.Renters()[0]

	// Clear the download history to make sure it's empty before we start the test.
	err := r.RenterClearAllDownloadsPost()
	if err != nil {
		t.Fatal(err)
	}

	// Upload a file.
	dataPieces := uint64(3)
	parityPieces := uint64(1)
	fileSize := int(modules.SectorSize)
Drexel's avatar
Drexel committed
316
	lf, rf, err := r.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
Christopher Schinnerl's avatar
Christopher Schinnerl committed
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}

	// This code sums up the 'received' variable in a similar way the renter
	// does it. We use it to find a fetchLen for which received != fetchLen due
	// to the implicit rounding of the unsigned integers.
	var fetchLen uint64
	for fetchLen = uint64(100); ; fetchLen++ {
		received := uint64(0)
		for piecesCompleted := uint64(1); piecesCompleted <= dataPieces; piecesCompleted++ {
			received += fetchLen / dataPieces
		}
		if received != fetchLen {
			break
		}
	}

	// Download fetchLen bytes of the file.
	_, err = r.DownloadToDiskPartial(rf, lf, false, 0, fetchLen)
	if err != nil {
		t.Fatal(err)
	}

	// Get the download.
	rdg, err := r.RenterDownloadsGet()
	if err != nil {
		t.Fatal(err)
	}
	d := rdg.Downloads[0]

	// Make sure that 'Received' matches the amount of data we fetched.
	if !d.Completed {
		t.Error("Download should be completed but wasn't")
	}
	if d.Received != fetchLen {
		t.Errorf("Received was %v but should be %v", d.Received, fetchLen)
	}
}

Matthew Sevey's avatar
Matthew Sevey committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
// testClearDownloadHistory makes sure that the download history is
// properly cleared when called through the API
func testClearDownloadHistory(t *testing.T, tg *siatest.TestGroup) {
	// Grab the first of the group's renters
	r := tg.Renters()[0]

	rdg, err := r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	numDownloads := 10
	if len(rdg.Downloads) < numDownloads {
		remainingDownloads := numDownloads - len(rdg.Downloads)
		rf, err := r.RenterFilesGet()
		if err != nil {
			t.Fatal(err)
		}
		// Check if the renter has any files
		// Upload a file if none
		if len(rf.Files) == 0 {
			dataPieces := uint64(1)
			parityPieces := uint64(1)
			fileSize := 100 + siatest.Fuzz()
Drexel's avatar
Drexel committed
380
			_, _, err := r.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
Matthew Sevey's avatar
Matthew Sevey committed
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
			if err != nil {
				t.Fatal("Failed to upload a file for testing: ", err)
			}
			rf, err = r.RenterFilesGet()
			if err != nil {
				t.Fatal(err)
			}
		}
		// Download files to build download history
		dest := filepath.Join(siatest.SiaTestingDir, strconv.Itoa(fastrand.Intn(math.MaxInt32)))
		for i := 0; i < remainingDownloads; i++ {
			err = r.RenterDownloadGet(rf.Files[0].SiaPath, dest, 0, rf.Files[0].Filesize, false)
			if err != nil {
				t.Fatal("Could not Download file:", err)
			}
		}
		rdg, err = r.RenterDownloadsGet()
		if err != nil {
			t.Fatal("Could not get download history:", err)
		}
		// Confirm download history is not empty
		if len(rdg.Downloads) != numDownloads {
			t.Fatalf("Not all downloads added to download history: only %v downloads added, expected %v", len(rdg.Downloads), numDownloads)
		}
	}
	numDownloads = len(rdg.Downloads)

	// Check removing one download from history
	// Remove First Download
	timestamp := rdg.Downloads[0].StartTime
	err = r.RenterClearDownloadsRangePost(timestamp, timestamp)
	if err != nil {
		t.Fatal("Error in API endpoint to remove download from history:", err)
	}
	numDownloads--
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	if len(rdg.Downloads) != numDownloads {
		t.Fatalf("Download history not reduced: history has %v downloads, expected %v", len(rdg.Downloads), numDownloads)
	}
	i := sort.Search(len(rdg.Downloads), func(i int) bool { return rdg.Downloads[i].StartTime.Equal(timestamp) })
	if i < len(rdg.Downloads) {
		t.Fatal("Specified download not removed from history")
	}
	// Remove Last Download
	timestamp = rdg.Downloads[len(rdg.Downloads)-1].StartTime
	err = r.RenterClearDownloadsRangePost(timestamp, timestamp)
	if err != nil {
		t.Fatal("Error in API endpoint to remove download from history:", err)
	}
	numDownloads--
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	if len(rdg.Downloads) != numDownloads {
		t.Fatalf("Download history not reduced: history has %v downloads, expected %v", len(rdg.Downloads), numDownloads)
	}
	i = sort.Search(len(rdg.Downloads), func(i int) bool { return rdg.Downloads[i].StartTime.Equal(timestamp) })
	if i < len(rdg.Downloads) {
		t.Fatal("Specified download not removed from history")
	}

	// Check Clear Before
	timestamp = rdg.Downloads[len(rdg.Downloads)-2].StartTime
	err = r.RenterClearDownloadsBeforePost(timestamp)
	if err != nil {
		t.Fatal("Error in API endpoint to clear download history before timestamp:", err)
	}
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	i = sort.Search(len(rdg.Downloads), func(i int) bool { return rdg.Downloads[i].StartTime.Before(timestamp) })
	if i < len(rdg.Downloads) {
		t.Fatal("Download found that was before given time")
	}

	// Check Clear After
	timestamp = rdg.Downloads[1].StartTime
	err = r.RenterClearDownloadsAfterPost(timestamp)
	if err != nil {
		t.Fatal("Error in API endpoint to clear download history after timestamp:", err)
	}
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	i = sort.Search(len(rdg.Downloads), func(i int) bool { return rdg.Downloads[i].StartTime.After(timestamp) })
	if i < len(rdg.Downloads) {
		t.Fatal("Download found that was after given time")
	}

	// Check clear range
	before := rdg.Downloads[1].StartTime
	after := rdg.Downloads[len(rdg.Downloads)-1].StartTime
	err = r.RenterClearDownloadsRangePost(after, before)
	if err != nil {
		t.Fatal("Error in API endpoint to remove range of downloads from history:", err)
	}
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	i = sort.Search(len(rdg.Downloads), func(i int) bool {
		return rdg.Downloads[i].StartTime.Before(before) && rdg.Downloads[i].StartTime.After(after)
	})
	if i < len(rdg.Downloads) {
		t.Fatal("Not all downloads from range removed from history")
	}

	// Check clearing download history
	err = r.RenterClearAllDownloadsPost()
	if err != nil {
		t.Fatal("Error in API endpoint to clear download history:", err)
	}
	rdg, err = r.RenterDownloadsGet()
	if err != nil {
		t.Fatal("Could not get download history:", err)
	}
	if len(rdg.Downloads) != 0 {
		t.Fatalf("Download history not cleared: history has %v downloads, expected 0", len(rdg.Downloads))
	}
}

508 509 510 511 512 513
// testDirectories checks the functionality of directories in the Renter
func testDirectories(t *testing.T, tg *siatest.TestGroup) {
	// Grab Renter
	r := tg.Renters()[0]

	// Test Directory endpoint for creating empty directory
514
	rd, err := r.UploadNewDirectory()
515 516 517 518
	if err != nil {
		t.Fatal(err)
	}

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
	// Check directory
	rgd, err := r.RenterGetDir(rd.SiaPath())
	if err != nil {
		t.Fatal(err)
	}
	// Directory should return 0 FileInfos and 1 DirectoryInfo with would belong
	// to the directory itself
	if len(rgd.Directories) != 1 {
		t.Fatal("Expected 1 DirectoryInfo to be returned but got:", len(rgd.Directories))
	}
	if rgd.Directories[0].SiaPath != rd.SiaPath() {
		t.Fatalf("SiaPaths do not match %v and %v", rgd.Directories[0].SiaPath, rd.SiaPath())
	}
	if len(rgd.Files) != 0 {
		t.Fatal("Expected no files in directory but found:", len(rgd.Files))
	}
535 536

	// Check uploading file to new subdirectory
537
	// Create local file
538
	size := 100 + siatest.Fuzz()
539 540
	fd := r.FilesDir()
	ld, err := fd.CreateDir("subDir1/subDir2/subDir3")
541
	if err != nil {
542 543
		t.Fatal(err)
	}
544
	lf, err := ld.NewFile(size)
545 546 547 548
	if err != nil {
		t.Fatal(err)
	}

549
	// Upload file
550 551
	dataPieces := uint64(1)
	parityPieces := uint64(1)
552 553 554 555 556 557 558 559
	rf, err := r.Upload(lf, dataPieces, parityPieces, false)
	if err != nil {
		t.Fatal(err)
	}

	// Check directory that file was uploaded to
	siaPath := filepath.Dir(rf.SiaPath())
	rgd, err = r.RenterGetDir(siaPath)
560 561 562
	if err != nil {
		t.Fatal(err)
	}
563 564 565 566 567 568 569
	// Directory should have 1 file and 0 sub directories
	if len(rgd.Directories) != 1 {
		t.Fatal("Expected 1 DirectoryInfo to be returned but got:", len(rgd.Directories))
	}
	if len(rgd.Files) != 1 {
		t.Fatal("Expected 1 file in directory but found:", len(rgd.Files))
	}
570

571 572 573 574 575 576 577 578 579 580 581 582
	// Check parent directory
	siaPath = filepath.Dir(siaPath)
	rgd, err = r.RenterGetDir(siaPath)
	if err != nil {
		t.Fatal(err)
	}
	// Directory should have 0 files and 1 sub directory
	if len(rgd.Directories) != 2 {
		t.Fatal("Expected 2 DirectoryInfos to be returned but got:", len(rgd.Directories))
	}
	if len(rgd.Files) != 0 {
		t.Fatal("Expected 0 files in directory but found:", len(rgd.Files))
583
	}
584 585 586 587 588 589 590 591 592 593 594

	// Test deleting directory
	if err = r.RenterDirDeletePost(rd.SiaPath()); err != nil {
		t.Fatal(err)
	}

	// Check that siadir was deleted from disk
	_, err = os.Stat(filepath.Join(r.RenterFilesDir(), rd.SiaPath()))
	if !os.IsNotExist(err) {
		t.Fatal("Expected IsNotExist err, but got err:", err)
	}
595 596
}

597 598 599 600 601 602 603 604 605
// testDownloadAfterRenew makes sure that we can still download a file
// after the contract period has ended.
func testDownloadAfterRenew(t *testing.T, tg *siatest.TestGroup) {
	// Grab the first of the group's renters
	renter := tg.Renters()[0]
	// Upload file, creating a piece for each host in the group
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces
	fileSize := 100 + siatest.Fuzz()
Drexel's avatar
Drexel committed
606
	_, remoteFile, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}
	// Mine enough blocks for the next period to start. This means the
	// contracts should be renewed and the data should still be available for
	// download.
	miner := tg.Miners()[0]
	for i := types.BlockHeight(0); i < siatest.DefaultAllowance.Period; i++ {
		if err := miner.MineBlock(); err != nil {
			t.Fatal(err)
		}
	}
	// Download the file synchronously directly into memory.
	_, err = renter.DownloadByStream(remoteFile)
	if err != nil {
		t.Fatal(err)
	}
}

626 627 628 629
// testDownloadMultipleLargeSectors downloads multiple large files (>5 Sectors)
// in parallel and makes sure that the downloads are blocking each other.
func testDownloadMultipleLargeSectors(t *testing.T, tg *siatest.TestGroup) {
	// parallelDownloads is the number of downloads that are run in parallel.
630
	parallelDownloads := 10
631 632
	// fileSize is the size of the downloaded file.
	fileSize := int(10*modules.SectorSize) + siatest.Fuzz()
633
	// set download limits and reset them after test.
634 635 636 637 638
	// uniqueRemoteFiles is the number of files that will be uploaded to the
	// network. Downloads will choose the remote file to download randomly.
	uniqueRemoteFiles := 5
	// Grab the first of the group's renters
	renter := tg.Renters()[0]
639
	// set download limits and reset them after test.
640
	if err := renter.RenterPostRateLimit(int64(fileSize)*2, 0); err != nil {
641 642 643
		t.Fatal("failed to set renter bandwidth limit", err)
	}
	defer func() {
644
		if err := renter.RenterPostRateLimit(0, 0); err != nil {
645 646 647
			t.Error("failed to reset renter bandwidth limit", err)
		}
	}()
648 649 650 651 652 653

	// Upload files
	dataPieces := uint64(len(tg.Hosts())) - 1
	parityPieces := uint64(1)
	remoteFiles := make([]*siatest.RemoteFile, 0, uniqueRemoteFiles)
	for i := 0; i < uniqueRemoteFiles; i++ {
Drexel's avatar
Drexel committed
654
		_, remoteFile, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
		if err != nil {
			t.Fatal("Failed to upload a file for testing: ", err)
		}
		remoteFiles = append(remoteFiles, remoteFile)
	}

	// Randomly download using download to file and download to stream methods.
	wg := new(sync.WaitGroup)
	for i := 0; i < parallelDownloads; i++ {
		wg.Add(1)
		go func() {
			var err error
			var rf = remoteFiles[fastrand.Intn(len(remoteFiles))]
			if fastrand.Intn(2) == 0 {
				_, err = renter.DownloadByStream(rf)
			} else {
				_, err = renter.DownloadToDisk(rf, false)
			}
			if err != nil {
				t.Error("Download failed:", err)
			}
			wg.Done()
		}()
	}
	wg.Wait()
}
681

682
// testLocalRepair tests if a renter correctly repairs a file from disk
683
// after a host goes offline.
684
func testLocalRepair(t *testing.T, tg *siatest.TestGroup) {
685 686 687
	// Grab the first of the group's renters
	renter := tg.Renters()[0]

688 689 690 691 692
	// Check that we have enough hosts for this test.
	if len(tg.Hosts()) < 2 {
		t.Fatal("This test requires at least 2 hosts")
	}

693 694 695 696 697 698
	// Set fileSize and redundancy for upload
	fileSize := int(modules.SectorSize)
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces

	// Upload file
Drexel's avatar
Drexel committed
699
	_, remoteFile, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
700 701 702 703
	if err != nil {
		t.Fatal(err)
	}
	// Get the file info of the fully uploaded file. Tha way we can compare the
704
	// redundancies later.
705
	fi, err := renter.File(remoteFile)
706 707 708 709 710 711 712 713 714 715 716 717
	if err != nil {
		t.Fatal("failed to get file info", err)
	}

	// Take down one of the hosts and check if redundancy decreases.
	if err := tg.RemoveNode(tg.Hosts()[0]); err != nil {
		t.Fatal("Failed to shutdown host", err)
	}
	expectedRedundancy := float64(dataPieces+parityPieces-1) / float64(dataPieces)
	if err := renter.WaitForDecreasingRedundancy(remoteFile, expectedRedundancy); err != nil {
		t.Fatal("Redundancy isn't decreasing", err)
	}
718 719 720 721 722 723
	// Mine a block to trigger the repair loop so the chunk is marked as stuck
	m := tg.Miners()[0]
	if err := m.MineBlock(); err != nil {
		t.Fatal(err)
	}
	// Check to see if a chunk got marked as stuck
724
	err = renter.WaitForStuckChunksToBubble()
725 726 727
	if err != nil {
		t.Fatal(err)
	}
728 729 730 731
	// We should still be able to download
	if _, err := renter.DownloadByStream(remoteFile); err != nil {
		t.Fatal("Failed to download file", err)
	}
732
	// Bring up a new host and check if redundancy increments again.
733 734
	_, err = tg.AddNodes(node.HostTemplate)
	if err != nil {
735 736 737 738 739
		t.Fatal("Failed to create a new host", err)
	}
	if err := renter.WaitForUploadRedundancy(remoteFile, fi.Redundancy); err != nil {
		t.Fatal("File wasn't repaired", err)
	}
740 741
	// Check to see if a chunk got repaired and marked as unstuck
	err = renter.WaitForStuckChunksToRepair()
742 743 744
	if err != nil {
		t.Fatal(err)
	}
745 746 747 748
	// We should be able to download
	if _, err := renter.DownloadByStream(remoteFile); err != nil {
		t.Fatal("Failed to download file", err)
	}
749 750
}

751
// testRemoteRepair tests if a renter correctly repairs a file by
752
// downloading it after a host goes offline.
753
func testRemoteRepair(t *testing.T, tg *siatest.TestGroup) {
754
	// Grab the first of the group's renters
755 756 757 758 759 760
	r := tg.Renters()[0]

	// Check that we have enough hosts for this test.
	if len(tg.Hosts()) < 2 {
		t.Fatal("This test requires at least 2 hosts")
	}
761 762 763 764 765 766 767

	// Set fileSize and redundancy for upload
	fileSize := int(modules.SectorSize)
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces

	// Upload file
Drexel's avatar
Drexel committed
768
	localFile, remoteFile, err := r.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
769 770 771 772 773
	if err != nil {
		t.Fatal(err)
	}
	// Get the file info of the fully uploaded file. Tha way we can compare the
	// redundancieslater.
774
	fi, err := r.File(remoteFile)
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
	if err != nil {
		t.Fatal("failed to get file info", err)
	}

	// Delete the file locally.
	if err := localFile.Delete(); err != nil {
		t.Fatal("failed to delete local file", err)
	}

	// Take down all of the parity hosts and check if redundancy decreases.
	for i := uint64(0); i < parityPieces; i++ {
		if err := tg.RemoveNode(tg.Hosts()[0]); err != nil {
			t.Fatal("Failed to shutdown host", err)
		}
	}
	expectedRedundancy := float64(dataPieces+parityPieces-1) / float64(dataPieces)
791
	if err := r.WaitForDecreasingRedundancy(remoteFile, expectedRedundancy); err != nil {
792 793
		t.Fatal("Redundancy isn't decreasing", err)
	}
794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
	// Mine a block to trigger the repair loop so the chunk is marked as stuck
	m := tg.Miners()[0]
	if err := m.MineBlock(); err != nil {
		t.Fatal(err)
	}
	// Check to see if a chunk got marked as stuck
	err = build.Retry(100, 100*time.Millisecond, func() error {
		fi2, err := r.File(remoteFile)
		if err != nil {
			return err
		}
		if fi2.NumStuckChunks == 0 {
			return errors.New("no stuck chunks found")
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
813
	// We should still be able to download
814
	if _, err := r.DownloadByStream(remoteFile); err != nil {
815
		t.Error("Failed to download file", err)
816
	}
817
	// Bring up new parity hosts and check if redundancy increments again.
818 819
	_, err = tg.AddNodeN(node.HostTemplate, int(parityPieces))
	if err != nil {
820 821
		t.Fatal("Failed to create a new host", err)
	}
822 823 824
	// When doing remote repair the redundancy might not reach 100%.
	expectedRedundancy = (1.0 - renter.RemoteRepairDownloadThreshold) * fi.Redundancy
	if err := r.WaitForUploadRedundancy(remoteFile, expectedRedundancy); err != nil {
825 826
		t.Fatal("File wasn't repaired", err)
	}
827 828 829 830 831 832 833 834 835 836 837 838 839 840
	// Check to see if a chunk got marked as unstuck
	err = build.Retry(100, 100*time.Millisecond, func() error {
		fi2, err := r.File(remoteFile)
		if err != nil {
			return err
		}
		if fi2.NumStuckChunks != 0 {
			return fmt.Errorf("%v stuck chunks found, expected 0", fi2.NumStuckChunks)
		}
		return nil
	})
	if err != nil {
		t.Fatal(err)
	}
841
	// We should be able to download
842
	if _, err := r.DownloadByStream(remoteFile); err != nil {
843 844
		t.Fatal("Failed to download file", err)
	}
845
}
846

847 848 849 850 851 852 853 854 855
// testSingleFileGet is a subtest that uses an existing TestGroup to test if
// using the single file API endpoint works
func testSingleFileGet(t *testing.T, tg *siatest.TestGroup) {
	// Grab the first of the group's renters
	renter := tg.Renters()[0]
	// Upload file, creating a piece for each host in the group
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces
	fileSize := 100 + siatest.Fuzz()
Drexel's avatar
Drexel committed
856
	_, _, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
857 858 859 860 861 862 863 864 865
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}

	files, err := renter.Files()
	if err != nil {
		t.Fatal("Failed to get renter files: ", err)
	}

866
	checks := 0
867
	for _, f := range files {
868
		// Only request files if file was fully uploaded for first API request
Matthew Sevey's avatar
Matthew Sevey committed
869 870 871 872
		if f.UploadProgress < 100 {
			continue
		}
		checks++
873
		rf, err := renter.RenterFileGet(f.SiaPath)
Matthew Sevey's avatar
Matthew Sevey committed
874 875 876
		if err != nil {
			t.Fatal("Failed to request single file", err)
		}
877 878 879 880 881

		// Can't use reflect.DeepEqual because certain fields are too dynamic,
		// however those fields are also not indicative of whether or not the
		// files are the same.  Not checking Redundancy, Available, Renewing
		// ,UploadProgress, UploadedBytes, or Renewing
882
		if f.Expiration != rf.File.Expiration {
883
			t.Log("File from Files() Expiration:", f.Expiration)
884
			t.Log("File from File() Expiration:", rf.File.Expiration)
885 886
			t.Fatal("Single file queries does not match file previously requested.")
		}
887
		if f.Filesize != rf.File.Filesize {
888
			t.Log("File from Files() Filesize:", f.Filesize)
889
			t.Log("File from File() Filesize:", rf.File.Filesize)
890 891
			t.Fatal("Single file queries does not match file previously requested.")
		}
892
		if f.LocalPath != rf.File.LocalPath {
893
			t.Log("File from Files() LocalPath:", f.LocalPath)
894
			t.Log("File from File() LocalPath:", rf.File.LocalPath)
895 896
			t.Fatal("Single file queries does not match file previously requested.")
		}
897
		if f.SiaPath != rf.File.SiaPath {
898
			t.Log("File from Files() SiaPath:", f.SiaPath)
899
			t.Log("File from File() SiaPath:", rf.File.SiaPath)
Matthew Sevey's avatar
Matthew Sevey committed
900
			t.Fatal("Single file queries does not match file previously requested.")
901 902
		}
	}
903 904 905
	if checks == 0 {
		t.Fatal("No files checks through single file endpoint.")
	}
906 907 908 909
}

// testStreamingCache checks if the chunk cache works correctly.
func testStreamingCache(t *testing.T, tg *siatest.TestGroup) {
910
	t.Skip("Caching is broken due to partial downloads")
911 912
	// Grab the first of the group's renters
	r := tg.Renters()[0]
913

914 915 916 917
	// Testing setting StreamCacheSize for streaming
	// Test setting it to larger than the defaultCacheSize
	if err := r.RenterSetStreamCacheSizePost(4); err != nil {
		t.Fatal(err, "Could not set StreamCacheSize to 4")
918
	}
919
	rg, err := r.RenterGet()
920
	if err != nil {
921
		t.Fatal(err)
922 923 924
	}
	if rg.Settings.StreamCacheSize != 4 {
		t.Fatal("StreamCacheSize not set to 4, set to", rg.Settings.StreamCacheSize)
925 926
	}

927 928 929 930 931
	// Test resetting to the value of defaultStreamCacheSize (2)
	if err := r.RenterSetStreamCacheSizePost(2); err != nil {
		t.Fatal(err, "Could not set StreamCacheSize to 2")
	}
	rg, err = r.RenterGet()
932
	if err != nil {
933
		t.Fatal(err)
934
	}
935 936
	if rg.Settings.StreamCacheSize != 2 {
		t.Fatal("StreamCacheSize not set to 2, set to", rg.Settings.StreamCacheSize)
937 938
	}

939 940 941 942 943 944 945
	prev := rg.Settings.StreamCacheSize

	// Test setting to 0
	if err := r.RenterSetStreamCacheSizePost(0); err == nil {
		t.Fatal(err, "expected setting stream cache size to zero to fail with an error")
	}
	rg, err = r.RenterGet()
946
	if err != nil {
947
		t.Fatal(err)
948 949 950
	}
	if rg.Settings.StreamCacheSize == 0 {
		t.Fatal("StreamCacheSize set to 0, should have stayed as previous value or", prev)
951 952
	}

953
	// Set fileSize and redundancy for upload
954
	ct := crypto.TypeDefaultRenter
955 956 957
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces

958
	// Set the bandwidth limit to 1 chunk per second.
959
	chunkSize := int64(siatest.ChunkSize(dataPieces, ct))
960
	if err := r.RenterPostRateLimit(chunkSize, chunkSize); err != nil {
961 962 963
		t.Fatal(err)
	}

964 965
	rg, err = r.RenterGet()
	if err != nil {
966
		t.Fatal(err)
967
	}
968 969
	if rg.Settings.MaxDownloadSpeed != chunkSize {
		t.Fatal(errors.New("MaxDownloadSpeed doesn't match value set through RenterPostRateLimit"))
970
	}
971 972
	if rg.Settings.MaxUploadSpeed != chunkSize {
		t.Fatal(errors.New("MaxUploadSpeed doesn't match value set through RenterPostRateLimit"))
973 974
	}

975
	// Upload a file that is a single chunk big.
Drexel's avatar
Drexel committed
976
	_, remoteFile, err := r.UploadNewFileBlocking(int(chunkSize), dataPieces, parityPieces, false)
977 978 979 980
	if err != nil {
		t.Fatal(err)
	}

981 982 983 984 985
	// Download the same chunk 250 times. This should take at least 250 seconds
	// without caching but not more than 30 with caching.
	start := time.Now()
	for i := 0; i < 250; i++ {
		if _, err := r.Stream(remoteFile); err != nil {
986 987
			t.Fatal(err)
		}
988 989 990
		if time.Since(start) > time.Second*30 {
			t.Fatal("download took longer than 30 seconds")
		}
991
	}
992 993 994 995 996 997 998 999 1000 1001 1002
	// Make sure that the stream downloads don't show up in the download
	// history.
	rgg, err := r.RenterDownloadsGet()
	if err != nil {
		t.Fatal(err)
	}
	for _, download := range rgg.Downloads {
		if download.DestinationType == "httpseekstream" {
			t.Fatal("Stream downloads shouldn't be added to the history")
		}
	}
1003
}
1004

1005
// testUploadDownload is a subtest that uses an existing TestGroup to test if
1006
// uploading and downloading a file works
1007
func testUploadDownload(t *testing.T, tg *siatest.TestGroup) {
1008
	// Grab the first of the group's renters
1009 1010 1011 1012
	renter := tg.Renters()[0]
	// Upload file, creating a piece for each host in the group
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces
1013
	fileSize := fastrand.Intn(2*int(modules.SectorSize)) + siatest.Fuzz() + 2 // between 1 and 2*SectorSize + 3 bytes
Drexel's avatar
Drexel committed
1014
	localFile, remoteFile, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
1015
	if err != nil {
1016
		t.Fatal("Failed to upload a file for testing: ", err)
1017
	}
1018 1019
	// Download the file synchronously directly into memory
	_, err = renter.DownloadByStream(remoteFile)
1020
	if err != nil {
1021
		t.Fatal(err)
1022
	}
1023 1024
	// Download the file synchronously to a file on disk
	_, err = renter.DownloadToDisk(remoteFile, false)
1025
	if err != nil {
1026 1027
		t.Fatal(err)
	}
1028 1029
	// Download the file asynchronously and wait for the download to finish.
	localFile, err = renter.DownloadToDisk(remoteFile, true)
1030
	if err != nil {
1031
		t.Error(err)
1032
	}
1033 1034
	if err := renter.WaitForDownload(localFile, remoteFile); err != nil {
		t.Error(err)
1035
	}
1036 1037
	// Stream the file.
	_, err = renter.Stream(remoteFile)
1038 1039 1040
	if err != nil {
		t.Fatal(err)
	}
1041 1042 1043 1044 1045 1046
	// Stream the file partially a few times. At least 1 byte is streamed.
	for i := 0; i < 5; i++ {
		from := fastrand.Intn(fileSize - 1)             // [0..fileSize-2]
		to := from + 1 + fastrand.Intn(fileSize-from-1) // [from+1..fileSize-1]
		_, err = renter.StreamPartial(remoteFile, localFile, uint64(from), uint64(to))
		if err != nil {
1047 1048 1049 1050
			t.Fatal(err)
		}
	}
}
1051

Drexel's avatar
Drexel committed
1052 1053 1054
// testUploadWithAndWithoutForceParameter is a subtest that uses an existing TestGroup to test if
// uploading an existing file is successful when setting 'force' to 'true' and 'force' set to 'false'
func testUploadWithAndWithoutForceParameter(t *testing.T, tg *siatest.TestGroup) {
1055 1056
	// Grab the first of the group's renters
	renter := tg.Renters()[0]
Drexel's avatar
Drexel committed
1057

1058 1059 1060 1061
	// Upload file, creating a piece for each host in the group
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces
	fileSize := 100 + siatest.Fuzz()
Drexel's avatar
Drexel committed
1062
	localFile, _, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
1063 1064 1065
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}
1066 1067 1068 1069
	//	_, err = renter.UploadBlocking(localFile, dataPieces, parityPieces, true)
	//	if err != nil {
	//		t.Fatal("Failed to force overwrite a file when specifying 'force=true': ", err)
	//	}
1070 1071

	// Upload file, creating a piece for each host in the group
Drexel's avatar
Drexel committed
1072 1073 1074
	dataPieces = uint64(1)
	parityPieces = uint64(len(tg.Hosts())) - dataPieces
	fileSize = 100 + siatest.Fuzz()
Drexel's avatar
Drexel committed
1075
	localFile, _, err = renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
1076 1077 1078
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}
Drexel's avatar
Drexel committed
1079
	_, err = renter.UploadBlocking(localFile, dataPieces, parityPieces, false)
Drexel's avatar
Drexel committed
1080 1081
	if err == nil {
		t.Fatal("File overwritten without specifying 'force=true'")
1082 1083 1084
	}
}

1085 1086 1087 1088 1089 1090 1091 1092
// testStreamLargeFile tests that using the streaming endpoint to download
// multiple chunks works.
func testStreamLargeFile(t *testing.T, tg *siatest.TestGroup) {
	// Grab the first of the group's renters
	renter := tg.Renters()[0]
	// Upload file, creating a piece for each host in the group
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts())) - dataPieces
1093 1094
	ct := crypto.TypeDefaultRenter
	fileSize := int(10 * siatest.ChunkSize(dataPieces, ct))
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
	localFile, remoteFile, err := renter.UploadNewFileBlocking(fileSize, dataPieces, parityPieces, false)
	if err != nil {
		t.Fatal("Failed to upload a file for testing: ", err)
	}
	// Stream the file partially a few times. At least 1 byte is streamed.
	for i := 0; i < 5; i++ {
		from := fastrand.Intn(fileSize - 1)             // [0..fileSize-2]
		to := from + 1 + fastrand.Intn(fileSize-from-1) // [from+1..fileSize-1]
		_, err = renter.StreamPartial(remoteFile, localFile, uint64(from), uint64(to))
		if err != nil {
			t.Fatal(err)
		}
	}
}

1110 1111 1112
// TestRenterInterrupt executes a number of subtests using the same TestGroup to
// save time on initialization
func TestRenterInterrupt(t *testing.T) {
1113
	if !build.VLONG {
1114 1115
		t.SkipNow()
	}
1116
	t.Parallel()
1117 1118 1119

	// Create a group for the subtests
	groupParams := siatest.GroupParams{
Matthew Sevey's avatar
Matthew Sevey committed
1120
		Hosts:  5,
1121
		Miners: 1,
1122 1123
	}

1124 1125
	// Specify sub tests
	subTests := []test{
1126
		{"TestContractInterruptedSaveToDiskAfterDeletion", testContractInterruptedSaveToDiskAfterDeletion},
1127 1128 1129 1130
		{"TestDownloadInterruptedAfterSendingRevision", testDownloadInterruptedAfterSendingRevision},
		{"TestDownloadInterruptedBeforeSendingRevision", testDownloadInterruptedBeforeSendingRevision},
		{"TestUploadInterruptedAfterSendingRevision", testUploadInterruptedAfterSendingRevision},
		{"TestUploadInterruptedBeforeSendingRevision", testUploadInterruptedBeforeSendingRevision},
1131
	}
1132 1133 1134 1135

	// Run tests
	if err := runRenterTests(t, groupParams, subTests); err != nil {
		t.Fatal(err)
1136 1137
	}
}
1138

1139 1140 1141 1142 1143 1144 1145
// testContractInterruptedSaveToDiskAfterDeletion runs testDownloadInterrupted with
// a dependency that interrupts the download after sending the signed revision
// to the host.
func testContractInterruptedSaveToDiskAfterDeletion(t *testing.T, tg *siatest.TestGroup) {
	testContractInterrupted(t, tg, newDependencyInterruptContractSaveToDiskAfterDeletion())
}

1146 1147 1148 1149 1150 1151 1152
// testDownloadInterruptedAfterSendingRevision runs testDownloadInterrupted with
// a dependency that interrupts the download after sending the signed revision
// to the host.
func testDownloadInterruptedAfterSendingRevision(t *testing.T, tg *siatest.TestGroup) {
	testDownloadInterrupted(t, tg, newDependencyInterruptDownloadAfterSendingRevision())
}

Matthew Sevey's avatar
Matthew Sevey committed
1153 1154 1155 1156 1157
// testDownloadInterruptedBeforeSendingRevision runs testDownloadInterrupted
// with a dependency that interrupts the download before sending the signed
// revision to the host.
func testDownloadInterruptedBeforeSendingRevision(t *testing.T, tg *siatest.TestGroup) {
	testDownloadInterrupted(t, tg, newDependencyInterruptDownloadBeforeSendingRevision())
1158 1159 1160 1161 1162 1163 1164 1165 1166
}

// testUploadInterruptedAfterSendingRevision runs testUploadInterrupted with a
// dependency that interrupts the upload after sending the signed revision to
// the host.
func testUploadInterruptedAfterSendingRevision(t *testing.T, tg *siatest.TestGroup) {
	testUploadInterrupted(t, tg, newDependencyInterruptUploadAfterSendingRevision())
}

Matthew Sevey's avatar
Matthew Sevey committed
1167 1168 1169 1170 1171 1172 1173
// testUploadInterruptedBeforeSendingRevision runs testUploadInterrupted with a
// dependency that interrupts the upload before sending the signed revision to
// the host.
func testUploadInterruptedBeforeSendingRevision(t *testing.T, tg *siatest.TestGroup) {
	testUploadInterrupted(t, tg, newDependencyInterruptUploadBeforeSendingRevision())
}

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
// testContractInterrupted interrupts a download using the provided dependencies.
func testContractInterrupted(t *testing.T, tg *siatest.TestGroup, deps *siatest.DependencyInterruptOnceOnKeyword) {
	// Add Renter
	testDir := renterTestDir(t.Name())
	renterTemplate := node.Renter(testDir + "/renter")
	renterTemplate.ContractorDeps = deps
	renterTemplate.Allowance = siatest.DefaultAllowance
	renterTemplate.Allowance.Period = 100
	renterTemplate.Allowance.RenewWindow = 75
	nodes, err := tg.AddNodes(renterTemplate)
	if err != nil {
		t.Fatal(err)
	}
	renter := nodes[0]

	// Call fail on the dependency every 10 ms.
	cancel := make(chan struct{})
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		for {
1195
			// Cause the contract renewal to fail
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
			deps.Fail()
			select {
			case <-cancel:
				wg.Done()
				return
			case <-time.After(10 * time.Millisecond):
			}
		}
	}()

	// Renew contracts.
	if err = renewContractsByRenewWindow(renter, tg); err != nil {
		t.Fatal(err)
	}

1211 1212 1213
	// Disrupt statement should prevent contracts from being renewed properly.
	// This means that both old and new contracts will be staticContracts which
	// are exported through the API via RenterContracts.Contracts
1214
	err = build.Retry(50, 100*time.Millisecond, func() error {
1215
		rc, err := renter.RenterContractsGet()
1216 1217 1218
		if err != nil {
			return err
		}
1219 1220
		if len(rc.Contracts) != len(tg.Hosts())*2 {
			return fmt.Errorf("Incorrect number of staticContracts: have %v expected %v", len(rc.Contracts), len(tg.Hosts())*2)
1221 1222 1223 1224
		}
		return nil
	})
	if err != nil {
1225
		renter.PrintDebugInfo(t, true, false, true)
1226 1227 1228 1229
		t.Fatal(err)
	}

	// By mining blocks to trigger threadContractMaintenance,
1230 1231 1232
	// managedCheckForDuplicates should move renewed contracts from
	// staticContracts to oldContracts even though disrupt statement is still
	// interrupting renew code.
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
	m := tg.Miners()[0]
	if err = m.MineBlock(); err != nil {
		t.Fatal(err)
	}
	if err = tg.Sync(); err != nil {
		t.Fatal(err)
	}
	err = build.Retry(70, 100*time.Millisecond, func() error {
		rc, err := renter.RenterInactiveContractsGet()
		if err != nil {
			return err
		}
		if len(rc.InactiveContracts) != len(tg.Hosts()) {
			return fmt.Errorf("Incorrect number of inactive contracts: have %v expected %v", len(rc.InactiveContracts), len(tg.Hosts()))
		}
		if len(rc.ActiveContracts) != len(tg.Hosts()) {
			return fmt.Errorf("Incorrect number of active contracts: have %v expected %v", len(rc.ActiveContracts), len(tg.Hosts()))
		}
1251 1252 1253
		if len(rc.Contracts) != len(tg.Hosts()) {
			return fmt.Errorf("Incorrect number of staticContracts: have %v expected %v", len(rc.Contracts), len(tg.Hosts()))
		}
1254 1255 1256 1257 1258 1259
		if err = m.MineBlock(); err != nil {
			return err
		}
		return nil
	})
	if err != nil {
1260
		renter.PrintDebugInfo(t, true, false, true)
1261 1262 1263 1264 1265 1266 1267 1268 1269
		t.Fatal(err)
	}

	// Stop calling fail on the dependency.
	close(cancel)
	wg.Wait()
	deps.Disable()
}

1270 1271 1272
// testDownloadInterrupted interrupts a download using the provided dependencies.
func testDownloadInterrupted(t *testing.T, tg *siatest.TestGroup, deps *siatest.DependencyInterruptOnceOnKeyword) {
	// Add Renter
1273
	testDir := renterTestDir(t.Name())
1274
	renterTemplate := node.Renter(testDir + "/renter")
Matthew Sevey's avatar
Matthew Sevey committed
1275
	renterTemplate.ContractSetDeps = deps
1276
	nodes, err := tg.AddNodes(renterTemplate)
1277 1278 1279
	if err != nil {
		t.Fatal(err)
	}
1280 1281 1282

	// Set the bandwidth limit to 1 chunk per second.
	renter := nodes[0]
1283
	ct := crypto.TypeDefaultRenter
1284 1285
	dataPieces := uint64(len(tg.Hosts())) - 1
	parityPieces := uint64(1)
1286
	chunkSize := siatest.ChunkSize(dataPieces, ct)
Drexel's avatar
Drexel committed
1287
	_, remoteFile, err := renter.UploadNewFileBlocking(int(chunkSize), dataPieces, parityPieces, false)
1288 1289 1290
	if err != nil {
		t.Fatal(err)
	}
1291
	if err := renter.RenterPostRateLimit(int64(chunkSize), int64(chunkSize)); err != nil {
1292 1293
		t.Fatal(err)
	}
1294

Christopher Schinnerl's avatar
Christopher Schinnerl committed
1295
	// Call fail on the dependency every 10 ms.
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
	cancel := make(chan struct{})
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		for {
			// Cause the next download to fail.
			deps.Fail()
			select {
			case <-cancel:
				wg.Done()
				return
			case <-time.After(10 * time.Millisecond):
			}
		}
	}()
	// Try downloading the file 5 times.
	for i := 0; i < 5; i++ {
		if _, err := renter.DownloadByStream(remoteFile); err == nil {
			t.Fatal("Download shouldn't succeed since it was interrupted")
		}
	}
	// Stop calling fail on the dependency.
	close(cancel)
	wg.Wait()
	deps.Disable()
	// Download the file once more successfully
	if _, err := renter.DownloadByStream(remoteFile); err != nil {
		t.Fatal("Failed to download the file", err)
	}
}

// testUploadInterrupted let's the upload fail using the provided dependencies
// and makes sure that this doesn't corrupt the contract.
func testUploadInterrupted(t *testing.T, tg *siatest.TestGroup, deps *siatest.DependencyInterruptOnceOnKeyword) {
	// Add Renter
1331
	testDir := renterTestDir(t.Name())
1332
	renterTemplate := node.Renter(testDir + "/renter")
Matthew Sevey's avatar
Matthew Sevey committed
1333
	renterTemplate.ContractSetDeps = deps
1334 1335
	nodes, err := tg.AddNodes(renterTemplate)
	if err != nil {
1336 1337 1338 1339
		t.Fatal(err)
	}

	// Set the bandwidth limit to 1 chunk per second.
1340
	ct := crypto.TypeDefaultRenter
1341
	renter := nodes[0]
1342 1343
	dataPieces := uint64(len(tg.Hosts())) - 1
	parityPieces := uint64(1)
1344
	chunkSize := siatest.ChunkSize(dataPieces, ct)
1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
	if err := renter.RenterPostRateLimit(int64(chunkSize), int64(chunkSize)); err != nil {
		t.Fatal(err)
	}

	// Call fail on the dependency every two seconds to allow some uploads to
	// finish.
	cancel := make(chan struct{})
	done := make(chan struct{})
	wg := new(sync.WaitGroup)
	wg.Add(1)
	go func() {
		defer close(done)
		// Loop until cancel was closed or we reach 5 iterations. Otherwise we
		// might end up blocking the upload for too long.
		for i := 0; i < 10; i++ {
			// Cause the next upload to fail.
			deps.Fail()
			select {
			case <-cancel:
				wg.Done()
				return
			case <-time.After(100 * time.Millisecond):
			}
		}
		wg.Done()
	}()

	// Upload a file that's 1 chunk large.
Drexel's avatar
Drexel committed
1373
	_, remoteFile, err := renter.UploadNewFileBlocking(int(chunkSize), dataPieces, parityPieces, false)
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
	if err != nil {
		t.Fatal(err)
	}
	// Make sure that the upload does not finish before the interrupting go
	// routine is finished
	select {
	case <-done:
	default:
		t.Fatal("Upload finished before interrupt signal is done")
	}
	// Stop calling fail on the dependency.
	close(cancel)
	wg.Wait()
	deps.Disable()
	// Download the file.
	if _, err := renter.DownloadByStream(remoteFile); err != nil {
		t.Fatal("Failed to download the file", err)
	}
}

Matthew Sevey's avatar
Matthew Sevey committed
1394
// TestRenterAddNodes runs a subset of tests that require adding their own renter
1395
func TestRenterAddNodes(t *testing.T) {
1396 1397 1398 1399 1400
	if testing.Short() {
		t.SkipNow()
	}
	t.Parallel()

1401
	// Create a group for testing
1402
	groupParams := siatest.GroupParams{
1403
		Hosts:   5,
1404 1405 1406 1407
		Renters: 1,
		Miners:  1,
	}

1408
	// Specify subtests to run
1409
	subTests := []test{
1410
		{"TestRedundancyReporting", testRedundancyReporting}, // Put first because it pulls the original tg renter
1411 1412
		{"TestRenterCancelAllowance", testRenterCancelAllowance},
		{"TestRenewFailing", testRenewFailing}, // Put last because it impacts a host
1413 1414
	}

1415 1416 1417
	// Run tests
	if err := runRenterTests(t, groupParams, subTests); err != nil {
		t.Fatal(err)
1418 1419 1420 1421 1422 1423
	}
}

// testRedundancyReporting verifies that redundancy reporting is accurate if
// contracts become offline.
func testRedundancyReporting(t *testing.T, tg *siatest.TestGroup) {
1424 1425 1426 1427 1428
	// Upload a file.
	dataPieces := uint64(1)
	parityPieces := uint64(len(tg.Hosts()) - 1)

	renter := tg.Renters()[0]
Drexel's avatar
Drexel committed
1429
	_, rf, err := renter.UploadNewFileBlocking(100, dataPieces, parityPieces, false)
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	if err != nil {
		t.Fatal(err)
	}

	// Stop a host.
	host := tg.Hosts()[0]
	if err := tg.StopNode(host); err != nil {
		t.Fatal(err)
	}

	// Mine a block to trigger contract maintenance.
	miner := tg.Miners()[0]
	if err := miner.MineBlock(); err != nil {
		t.Fatal(err)
	}

	// Redundancy should decrease.
	expectedRedundancy := float64(dataPieces+parityPieces-1) / float64(dataPieces)
	if err := renter.WaitForDecreasingRedundancy(rf, expectedRedundancy); err != nil {
		t.Fatal("Redundancy isn't decreasing", err)
	}

	// Restart the host.
	if err := tg.StartNode(host); err != nil {
		t.Fatal(err)
	}

	// Wait until the host shows up as active again.
	pk, err := host.HostPublicKey()
	if err != nil {
		t.Fatal(err)
	}
	err = build.Retry(60, time.Second, func() error {
		hdag, err := renter.HostDbActiveGet()